一、XML

1.1 application.xml配置文件

其中写了依赖关系。如:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. https://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <bean id="userService" class="com.itranswarp.learnjava.service.UserService">
  7. <property name="mailService" ref="mailService" />
  8. </bean>
  9. <bean id="mailService" class="com.itranswarp.learnjava.service.MailService" />
  10. </beans>

以下代码表明userService依赖mailService

  1. <bean id="userService" class="com.itranswarp.learnjava.service.UserService">
  2. <property name="mailService" ref="mailService" />
  3. </bean>

1.2 例子

  1. public class Main {
  2. public static void main(String[] args) {
  3. ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
  4. UserService userService = context.getBean(UserService.class);
  5. User user = userService.login("bob@example.com", "password");
  6. System.out.println(user.getName());
  7. }
  8. }

Spring容器就是ApplicationContext

- ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");读取application.xml文件。
- UserService userService = context.getBean(UserService.class);根据Bean的类型获取Bean

二、Annotation

2.1 类

  1. @Component
  2. public class UserService {
  3. @Autowired
  4. MailService mailService;
  5. ...
  6. }

@Component表示此类是个Bean
@Autowired将把指定类型的Bean注入到指定的字段中。

2.2 main

  1. @Configuration
  2. @ComponentScan
  3. public class AppConfig {
  4. public static void main(String[] args) {
  5. ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
  6. UserService userService = context.getBean(UserService.class);
  7. User user = userService.login("bob@example.com", "password");
  8. System.out.println(user.getName());
  9. }
  10. }
  • @Configuration表明AppConfig是一个配置类。作为ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);的参数。
  • @ComponentScan告诉容器,自动搜索当前类所在的包以及子包,把所有标注为@ComponentBean自动创建出来,并根据@Autowired进行装配。

    参考

  1. 装配Bean - 廖雪峰的官方网站