全注解方式加载 Spring 配置
Spring Boot 推荐我们使用全注解的方式加载 Spring 配置,其实现方式如下:
- 使用 @Configuration 注解定义配置类,替换 Spring 的配置文件;
- 配置类内部可以包含有一个或多个被 @Bean 注解的方法,这些方法会被 AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext 类扫描,构建 bean 定义(相当于 Spring 配置文件中的<bean></bean>标签),方法的返回值会以组件的形式添加到容器中,组件的 id 就是方法名。
以 helloworld 为例,删除主启动类的 @ImportResource 注解,在 net.biancheng.www.config 包下添加一个名为 MyAppConfig 的配置类,代码如下。
- package net.biancheng.www.config;
- import net.biancheng.www.service.PersonService;
- import net.biancheng.www.service.impl.PersonServiceImpl;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- /**
- * @Configuration 注解用于定义一个配置类,相当于 Spring 的配置文件
- * 配置类中包含一个或多个被 @Bean 注解的方法,该方法相当于 Spring 配置文件中的 <bean> 标签定义的组件。
- */
- @Configuration
- public class MyAppConfig {
- /**
- * 与 <bean id="personService" class="PersonServiceImpl"></bean> 等价
- * 该方法返回值以组件的形式添加到容器中
- * 方法名是组件 id(相当于 <bean> 标签的属性 id)
- */
- @Bean
- public PersonService personService() {
- System.out.println("在容器中添加了一个组件:peronService");
- return new PersonServiceImpl();
- }
- }