基于注解的配置
从 Spring 2.5 开始就可以使用注解来配置依赖注入。而不是采用 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>
@Required 注释应用于 bean 属性的 setter 方法,它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常。
下面显示的是一个使用 @Required 注释的示例
下面是 Student.java 文件的内容:
package com.spring.chapter5; import java.util.List;
import java.util.Set; import org.springframework.beans.factory.annotation.Required; public class Student { public String getName() {
return name;
}
@Required
public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
}
@Required
public void setAge(int age) {
this.age = age;
}
private String name;
private int age; }
下面是 MainApp.java 文件的内容:
package com.spring.chapter5; import java.util.List; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main {
/**
* Spring @Required 注解注入
* author:
* mail:2536201485@qq.com
* 时间:
*/ public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring_xml/spring.xml");
Student student=(Student)applicationContext.getBean("student");
System.out.println("名字是:"+student.getName());
System.out.println("年龄是:"+student.getAge()); } }
下面是配置文件 Beans.xml: 文件的内容: 上面的头信息就省略了
<!-- @Required 注解 --> <bean id="student" class="com.spring.chapter5.Student">
<property name="name" value="张三"></property>
<!-- age属性 -->
<!-- <property name="age" value="24"></property> -->
</bean>
@Required 注释应用于 bean 属性的 setter 方法,它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常。下面显示的是一个使用 @Required 注释的示例,当中setAge()方法标注了当中age的属性配置被注销了。所以会报 BeanInitializationException 异常。在生产规模的应用程序中,IoC容器中可能会有数百或数千个bean,并且它们之间的依赖关系通常非常复杂。setter注入的一个缺点是你很难检查是否已经设置了所有必需的属性
运行结果:
名字是:张三
年龄是:24
注意:在使用@Required注解注入时,我们需要添加spring-aop的依赖包