目录

基于注释的配置(Annotation Based Configuration)

从Spring 2.5开始,可以使用annotations配置依赖注入。 因此,不是使用XML来描述bean连接,而是可以通过在相关的类,方法或字段声明上使用注释将bean配置移动到组件类本身。

在注入XML之前执行注释注入。 因此,对于通过两种方法连接的属性,后一种配置将覆盖前者。

默认情况下,Spring容器中未打开注释接线。 因此,在我们使用基于注释的布线之前,我们需要在Spring配置文件中启用它。 因此,如果要在Spring应用程序中使用任何注释,请考虑以下配置文件。

<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context = "http://www.springframework.org/schema/context"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   <context:annotation-config/>
   <!-- bean definitions go here -->
</beans>

一旦配置了,就可以开始注释代码,以指示Spring应该自动将值连接到属性,方法和构造函数中。 让我们看一些重要的注释来理解它们是如何工作的 -

Sr.No. 注释和说明
1 @Required

@Required注释适用于bean属性setter方法。

2 @Autowired

@Autowired注释可以应用于bean属性setter方法,非setter方法,构造函数和属性。

3 @Qualifier

@Qualifier注释和@Autowired可用于通过指定将连接哪个确切的bean来消除混淆。

4 JSR-250注释

Spring支持基于JSR-250的注释,包括@ Resource,@ PostConstruct和@PreDestroy注释。

↑回到顶部↑
WIKI教程 @2018