一、XML
1.1 application.xml
配置文件
其中写了依赖关系。如:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userService" class="com.itranswarp.learnjava.service.UserService">
<property name="mailService" ref="mailService" />
</bean>
<bean id="mailService" class="com.itranswarp.learnjava.service.MailService" />
</beans>
以下代码表明userService
依赖mailService
<bean id="userService" class="com.itranswarp.learnjava.service.UserService">
<property name="mailService" ref="mailService" />
</bean>
1.2 例子
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
UserService userService = context.getBean(UserService.class);
User user = userService.login("bob@example.com", "password");
System.out.println(user.getName());
}
}
Spring
容器就是ApplicationContext
- ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
读取application.xml
文件。- UserService userService = context.getBean(UserService.class);
根据Bean
的类型获取Bean
。
二、Annotation
2.1 类
@Component
public class UserService {
@Autowired
MailService mailService;
...
}
@Component
表示此类是个Bean
。@Autowired
将把指定类型的Bean注入到指定的字段中。
2.2 main
@Configuration
@ComponentScan
public class AppConfig {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
User user = userService.login("bob@example.com", "password");
System.out.println(user.getName());
}
}