SpringBoot中的注解
通过下面的代码来讲下
@Component // 用于将 Person 类作为 Bean 注入到 Spring 容器中
@ConfigurationProperties(prefix = "person") // 将配置文件中以 person 开头的属性注入到该类中
public class Person {
private int id; // id
private String name; // 名称
private List hobby; // 爱好
private String[] family; // 家庭成员
private Map map;
private Pet pet; // 宠物
// 省略属性 getter 和 setter 方法
// 省略 toString() 方法@Component 是将符合Bean规范(上面的Person类就是很好的符合了)的类对象作为Bean组件放到Spring容器中,其根本目的是让Spring Boot可以自动扫描到该组件,然后进行其他功能实现。
@ConfigurationProperties(prefix = "person")作用是将配置文件(在resource目录中)中以person开头的属性值通过setter方法注入实体类对应的属性中。
@Configuration // 定义该类是一个配置类
public class DataSourceConfig {
@Bean // 将返回值对象作为组件添加到 Spring 容器中,该组件 id 默认为方法名
@ConfigurationProperties(prefix = "spring.datasource") // 上面刚刚讲完
public DataSource getDruid() {
return new DruidDataSource();
}
}@Configuration 是注解声明这是一个配置类,该配置类会被Spring Boot自动扫描识别。
@Bean 将返回值对象作为组件添加到 Spring 容器中,该组件 id 默认为方法名,上面的示例中,id就是getDruid。
然后就是测试这个配置类是否被识别到了。
...
import org.springframework.context.ApplicationContext;
...
@RunWith(SpringRunner.class) // 让测试运行于 Spring 测试环境
@SpringBootTest // Spring 单元测试注解
class ApplicationTests {
@Autowired // 自动装配,在该测试类中引入 ApplicationContext 实体类 Bean
private ApplicationContext applicationContext;
@Test
public void iocTest() {
System.out.println(applicationContext.containsBean("getDruid"));
}
}如果结果为true,说明该自定义配置已被识别到。
评论已关闭