-
@Configuration
:表明这是一个注解类,可以使用AnnotationConfigApplicationContext
来获得一个上下文对象,传入的参数为注解类本身
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(BeanConfiguration.class);
-
@Bean
:表明这是一个实体类对象,一般配置在注解的Java文件中
@Bean
public Divided createDivided() {
return new Divided();
}
返回一个实体对象,与xml中的配置一样,如果需要引入其他的对象注入,可以直接说明:
@Bean
public Divided createDivided(Math math) {
return new Divided(math);
}
这里传入了一个其他的对象,Spring在得到对象时,会自动注入
3. @Autowired
:自动注入Spring环境存在的bean对象
4. @Named
:与 @Autowired
类似,但是这是Java规范,不是Spring规范
5. @Inject
:Java规范注解,也可直接注入对象
6. @Reource
:Java规范注解,可注入对象,一般建议什么环境,使用什么注解。
7. @Primary
:如果存在冲突Bean对象,优先注入该对象
8. @Controller
:表明这是一个web层的组件,但是使用@Service
注解,也不会有影响,但是推荐什么层使用什么注解。
9. @Service
:服务层注解
10. @Repository
:dao层注解
11. @Component
: 表明这是一个普通组件,当一个Bean对象,不想通过@Bean
的方式注入时,可以使用此注解,以上四个注解,如果未声明到配置文件中,需要自动扫描注解对象。
12. @ComponentScan(basePackages = "property.entity")
:可传入多个包的值,表明那些包均会被扫描到Spring容器中
13. @Import(value = DataConfiguration.class)
:可引入其他的配置类,或者引入其他的Bean对象,但是建议使用该注解,只引用配置类
14. @importResource(value="classpath:/applicationContext.xml")
:引入xml配置文件
15. @PropertySource(value = {"classpath:/jdbc.properties"})
:引用外部配置文件,spEL需要获得配置文件中的值,可以使用@Value("${jdbc.url.suffix}")
,如果需要进行spEl运算,可以使用@Value("#{1+1}")
16. @ConfigurationProperties
可直接配置字符串前缀,可输入或不输入后缀,便可实现字符串的注入
@Configuration
@PropertySource(value = {"classpath:/jdbc.properties"})
@ConfigurationProperties("prefix="book"")
class Bean {
}
- 引入该jar包,可能够把application.properties文件进行注入
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
-
@Profile(value="test")
:环境注解,在适当的环境下,该Bean对象才会被注入:
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.getEnvironment().setActiveProfiles("test");
applicationContext.register(BeanConfiguration.class);
applicationContext.refresh();
或者需要在测试类中进行使用,使用@ActiveProfiles
注解进行配置环境
19. @Conditional(WindowCondition.class)
:条件注解,当满足条件时,才会被注入,与@Profile
不同,Profile
可以是用在数据库等方面,@Conditional
可以考虑在跨平台时使用。
20. Spring测试,需要引入spring-test
和junit
两个包,然后配置
@RunWith(SpringJunit4ClassRunner.class)
@ContextConfiguration(BeanConfiguration.class)
public class TestApplication() {
}