基于注解的配置
从 Spring 2.5 开始就可以使用注解来配置依赖注入。而不是采用 XML 来描述一个 bean 连线,你可以使用相关类,方法或字段声明的注解,将 bean 配置移动到组件类本身。
在 XML 注入之前进行注解注入,因此后者的配置将通过两种方式的属性连线被前者重写。
注解连线在默认情况下在 Spring 容器中不打开。因此,在可以使用基于注解的连线之前,我们将需要在我们的 Spring 配置文件中启用它。所以如果你想在 Spring 应用程序中使用的任何注解,可以考虑到下面的配置文件。
1 <?xml version="1.0" encoding="UTF-8"?>
2
3
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xmlns:context="http://www.springframework.org/schema/context"
6 xsi:schemaLocation="http://www.springframework.org/schema/beans7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd8 http://www.springframework.org/schema/context9 http://www.springframework.org/schema/context/spring-context-3.0.xsd">
10
11
12
13
14
@Required 注释应用于 bean 属性的 setter 方法,它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常。
下面显示的是一个使用 @Required 注释的示例
下面是 Student.java 文件的内容:
1 packagecom.spring.chapter5;2
3 importjava.util.List;4 importjava.util.Set;5
6 importorg.springframework.beans.factory.annotation.Required;7
8
9
10 public classStudent {11
12 publicString getName() {13 returnname;14 }15 @Required16 public voidsetName(String name) {17 this.name =name;18 }19
20 public intgetAge() {21 returnage;22 }23 @Required24 public void setAge(intage) {25 this.age =age;26 }27 privateString name;28 private intage;29
30
31
32 }
下面是 MainApp.java 文件的内容:
1 packagecom.spring.chapter5;2
3
4 importjava.util.List;5
6 importorg.springframework.context.ApplicationContext;7 importorg.springframework.context.support.AbstractApplicationContext;8 importorg.springframework.context.support.ClassPathXmlApplicationContext;9
10 public classMain {11 /**
12 * Spring @Required 注解注入13 * author:14 * mail:2536201485@qq.com15 * 时间:16 */
17
18 public static voidmain(String[] args) {19 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring_xml/spring.xml");20 Student student=(Student)applicationContext.getBean("student");21 System.out.println("名字是:"+student.getName());22 System.out.println("年龄是:"+student.getAge());23
24
25 }26
27 }
下面是配置文件 Beans.xml: 文件的内容: 上面的头信息就省略了
@Required 注释应用于 bean 属性的 setter 方法,它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常。下面显示的是一个使用 @Required 注释的示例,当中setAge()方法标注了当中age的属性配置被注销了。所以会报 BeanInitializationException 异常。在生产规模的应用程序中,IoC容器中可能会有数百或数千个bean,并且它们之间的依赖关系通常非常复杂。setter注入的一个缺点是你很难检查是否已经设置了所有必需的属性
运行结果:
名字是:张三
年龄是:24
注意:在使用@Required注解注入时,我们需要添加spring-aop的依赖包