大三学习进度9

全注解方式加载 Spring 配置

Spring Boot 推荐我们使用全注解的方式加载 Spring 配置,其实现方式如下:

  1. 使用 @Configuration 注解定义配置类,替换 Spring 的配置文件;
  2. 配置类内部可以包含有一个或多个被 @Bean 注解的方法,这些方法会被 AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext 类扫描,构建 bean 定义(相当于 Spring 配置文件中的<bean></bean>标签),方法的返回值会以组件的形式添加到容器中,组件的 id 就是方法名。


以 helloworld 为例,删除主启动类的 @ImportResource 注解,在 net.biancheng.www.config 包下添加一个名为  MyAppConfig 的配置类,代码如下。

  1. package net.biancheng.www.config;
  2. import net.biancheng.www.service.PersonService;
  3. import net.biancheng.www.service.impl.PersonServiceImpl;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. /**
  7. * @Configuration 注解用于定义一个配置类,相当于 Spring 的配置文件
  8. * 配置类中包含一个或多个被 @Bean 注解的方法,该方法相当于 Spring 配置文件中的 <bean> 标签定义的组件。
  9. */
  10. @Configuration
  11. public class MyAppConfig {
  12. /**
  13. * 与 <bean id="personService" class="PersonServiceImpl"></bean> 等价
  14. * 该方法返回值以组件的形式添加到容器中
  15. * 方法名是组件 id(相当于 <bean> 标签的属性 id)
  16. */
  17. @Bean
  18. public PersonService personService() {
  19. System.out.println("在容器中添加了一个组件:peronService");
  20. return new PersonServiceImpl();
  21. }
  22. }
原文地址:https://www.cnblogs.com/hhw12345/p/14157494.html