基于注解的配置

从 Spring 2.5 开始就可以使用注解来配置依赖注入。而不是采用 XML 来描述一个 bean 连线,你可以使用相关类,方法或字段声明的注解,将 bean 配置移动到组件类本身。

在 XML 注入之前进行注解注入,因此后者的配置将通过两种方式的属性连线被前者重写。

一、@Required注解

@Required 注解应用于 bean 属性的 setter 方法,它表明受影响的 bean 属性在配置时必须放在 XML 配置文件中,否则容器就会抛出一个 BeanInitializationException 异常。下面显示的是一个使用 @Required 注解的示例。

(1)编写Student.java

  1. package com.tutorialspoint;
  2. import org.springframework.beans.factory.annotation.Required;
  3. public class Student {
  4. private Integer age;
  5. private String name;
  6. @Required
  7. public void setAge(Integer age) {
  8. this.age = age;
  9. }
  10. public Integer getAge() {
  11. return age;
  12. }
  13. @Required
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. }

(2)编写MainApp.java

  1. package com.tutorialspoint;
  2.  
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5.  
  6. public class MainApp {
  7. public static void main(String[] args) {
  8. ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
  9. Student student = (Student) context.getBean("student");
  10. System.out.println("Name : " + student.getName() );
  11. System.out.println("Age : " + student.getAge() );
  12. }}

(3)编写Beans.xml

  1. <?xml version = "1.0" encoding = "UTF-8"?>
  2.  
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  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/beans
  7. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  10.  
  11. <context:annotation-config/>
  12.  
  13. <!-- Definition for student bean -->
  14. <bean id="student" class="com.tutorialspoint.Student">
  15. <property name="name" value="Zara" />
  16.  
  17. <!-- try without passing age and check the result -->
  18. <property name="age" value="11"/>
  19. </bean>
  20.  
  21. </beans>

(4)运行MainApp.java中的main方法

如图:

这是正常流程

异常流程只需将Beans.xml改成如下,再运行main方法:

  1. <?xml version = "1.0" encoding = "UTF-8"?>
  2.  
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  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/beans
  7. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  10.  
  11. <context:annotation-config/>
  12.  
  13. <!-- Definition for student bean -->
  14. <bean id="student" class="com.tutorialspoint.Student">
  15. <property name="name" value="Zara" />
  16.  
  17. <!-- try without passing age and check the result -->
  18. <!--<property name="age" value="11"/>-->
  19. </bean>
  20.  
  21. </beans>

控制台最后的结果如下:

我想大家应该明白了,@Required注解的作用,其实这个注解与input中的required属性倒有其相同点,必填不能为空。

二、AutoWired注解

@Autowired 注释对在哪里和如何完成自动连接提供了更多的细微的控制。

@Autowired 注释可以在 setter 方法中被用于自动连接 bean,就像 @Autowired 注释,容器,一个属性或者任意命名的可能带有多个参数的方法。

演示示例:

1.编写TextEditor.java

  1. package com.tutorialspoint;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. public class TextEditor {
  4. private SpellChecker spellChecker;
  5. @Autowired
  6. public void setSpellChecker( SpellChecker spellChecker ){
  7. this.spellChecker = spellChecker;
  8. }
  9. public SpellChecker getSpellChecker( ) {
  10. return spellChecker;
  11. }
  12. public void spellCheck() {
  13. spellChecker.checkSpelling();
  14. }
  15. }

2.编写SpellChecker.java

  1. package com.tutorialspoint;
  2. public class SpellChecker {
  3. public SpellChecker(){
  4. System.out.println("Inside SpellChecker constructor." );
  5. }
  6. public void checkSpelling(){
  7. System.out.println("Inside checkSpelling." );
  8. }
  9. }

3.编写Beans.xml

  1. <?xml version = "1.0" encoding = "UTF-8"?>
  2.  
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  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/beans
  7. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  10.  
  11. <context:annotation-config/>
  12.  
  13. <!-- Definition for textEditor bean without constructor-arg -->
  14. <bean id="textEditor" class="com.tutorialspoint.TextEditor">
  15. </bean>
  16.  
  17. <!-- Definition for spellChecker bean -->
  18. <bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
  19. </bean>
  20.  
  21. </beans>

4.编写MainApp.java

  1. package com.tutorialspoint;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. public class MainApp {
  5. public static void main(String[] args) {
  6. ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
  7. TextEditor te = (TextEditor) context.getBean("textEditor");
  8. te.spellCheck();
  9. }
  10. }

5.运行MainApp.java中的main方法

结果如下:

@AutoWired 自动装配 它的一个属性叫required,属性值是boolean类型,默认为true,必须,也可以修改为false,非必须。

三、Qualifier注解

可能会有这样一种情况,当你创建多个具有相同类型的 bean 时,并且想要用一个属性只为它们其中的一个进行装配,在这种情况下,你可以使用 @Qualifier 注释和 @Autowired 注释通过指定哪一个真正的 bean 将会被装配来消除混乱。下面显示的是使用 @Qualifier 注释的一个示例。

(1)编写Student.java

  1. package com.tutorialspoint;
  2. public class Student {
  3. private Integer age;
  4. private String name;
  5. public void setAge(Integer age) {
  6. this.age = age;
  7. }
  8. public Integer getAge() {
  9. return age;
  10. }
  11. public void setName(String name) {
  12. this.name = name;
  13. }
  14. public String getName() {
  15. return name;
  16. }
  17. }

(2)编写Profile.java

  1. package com.tutorialspoint;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Qualifier;
  5.  
  6. public class Profile {
  7. @Autowired
  8. @Qualifier("student1")
  9. private Student student;
  10. public Profile(){
  11. System.out.println("Inside Profile constructor." );
  12. }
  13. public void printAge() {
  14. System.out.println("Age : " + student.getAge() );
  15. }
  16. public void printName() {
  17. System.out.println("Name : " + student.getName() );
  18. }
  19. }

(3)编写MainApp.java

  1. package com.tutorialspoint;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. public class MainApp {
  5. public static void main(String[] args) {
  6. ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
  7. Profile profile = (Profile) context.getBean("profile");
  8. profile.printAge();
  9. profile.printName();
  10. }
  11. }

(4)编写Beans.xml

  1. <?xml version = "1.0" encoding = "UTF-8"?>
  2.  
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  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/beans
  7. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  10.  
  11. <context:annotation-config/>
  12.  
  13. <!-- Definition for profile bean -->
  14. <bean id="profile" class="com.tutorialspoint.Profile">
  15. </bean>
  16.  
  17. <!-- Definition for student1 bean -->
  18. <bean id="student1" class="com.tutorialspoint.Student">
  19. <property name="name" value="Zara" />
  20. <property name="age" value="11"/>
  21. </bean>
  22.  
  23. <!-- Definition for student2 bean -->
  24. <bean id="student2" class="com.tutorialspoint.Student">
  25. <property name="name" value="Nuha" />
  26. <property name="age" value="2"/>
  27. </bean>
  28.  
  29. </beans>

(5)运行MainApp.java对应的main方法

四、Spring JSR-250 注释

Spring还使用基于 JSR-250 注释,它包括 @PostConstruct, @PreDestroy 和 @Resource 注释。因为你已经有了其他的选择,尽管这些注释并不是真正所需要的,但是关于它们仍然让我给出一个简短的介绍。

@PostConstruct 和 @PreDestroy 注释:

为了定义一个 bean 的安装和卸载,我们使用 init-method 和/或 destroy-method 参数简单的声明一下 。init-method 属性指定了一个方法,该方法在 bean 的实例化阶段会立即被调用。同样地,destroy-method 指定了一个方法,该方法只在一个 bean 从容器中删除之前被调用。

你可以使用 @PostConstruct 注释作为初始化回调函数的一个替代,@PreDestroy 注释作为销毁回调函数的一个替代,其解释如下示例所示。

演示示例:

(1)编写HelloWorld.java

  1. package com.tutorialspoint;
  2. import javax.annotation.*;
  3. public class HelloWorld {
  4. private String message;
  5. public void setMessage(String message){
  6. this.message = message;
  7. }
  8. public String getMessage(){
  9. System.out.println("Your Message : " + message);
  10. return message;
  11. }
  12. @PostConstruct
  13. public void init(){
  14. System.out.println("Bean is going through init.");
  15. }
  16. @PreDestroy
  17. public void destroy(){
  18. System.out.println("Bean will destroy now.");
  19. }
  20. }

(2)编写Beans.xml

  1. <?xml version = "1.0" encoding = "UTF-8"?>
  2.  
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  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/beans
  7. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  10.  
  11. <context:annotation-config/>
  12.  
  13. <bean id="helloWorld"
  14. class="com.tutorialspoint.HelloWorld"
  15. init-method="init" destroy-method="destroy">
  16. <property name="message" value="Hello World!"/>
  17. </bean>
  18.  
  19. </beans>

(3)编写MainApp.java并运行对应的main方法

  1. package com.tutorialspoint;
  2. import org.springframework.context.support.AbstractApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4.  
  5. public class MainApp {
  6. public static void main(String[] args) {
  7. AbstractApplicationContext context =
  8. new ClassPathXmlApplicationContext("Beans.xml");
  9. HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
  10. obj.getMessage();
  11. context.registerShutdownHook();
  12. }
  13. }

结果如图:

Spring(七)之基于注解配置的更多相关文章

  1. Spring 使用AOP——基于注解配置

    首先,使用注解实现AOP是基于AspectJ方式的. 创建包含切点方法的类 package cn.ganlixin.test; import org.aspectj.lang.annotation.P ...

  2. Unit03: Spring Web MVC简介 、 基于XML配置的MVC应用 、 基于注解配置的MVC应用

    Unit03: Spring Web MVC简介 . 基于XML配置的MVC应用 . 基于注解配置的MVC应用 springmvc (1)springmvc是什么? 是一个mvc框架,用来简化基于mv ...

  3. 使用 Spring 2.5 基于注解驱动的 Spring MVC

    http://www.ibm.com/developerworks/cn/java/j-lo-spring25-mvc/ 概述 继 Spring 2.0 对 Spring MVC 进行重大升级后,Sp ...

  4. 使用 Spring 2.5 基于注解驱动的 Spring MVC--转

    概述 继 Spring 2.0 对 Spring MVC 进行重大升级后,Spring 2.5 又为 Spring MVC 引入了注解驱动功能.现在你无须让 Controller 继承任何接口,无需在 ...

  5. Spring学习之旅(七)基于XML配置与基于AspectJ注解配置的AOP编程比较

    本篇博文用一个稍复杂点的案例来对比一下基于XML配置与基于AspectJ注解配置的AOP编程的不同. 相关引入包等Spring  AOP编程准备,请参考小编的其他博文,这里不再赘述. 案例要求: 写一 ...

  6. Spring学习记录(十二)---AOP理解和基于注解配置

    Spring核心之二:AOP(Aspect Oriented Programming) --- 面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP是OOP的延续,是软 ...

  7. Spring IOC之基于注解的容器配置

    Spring配置中注解比XML更好吗?基于注解的配置的介绍提出的问题是否这种途径比XML更好.简单来说就是视情况而定. 长一点的答案是每一种方法都有自己的长处也不足,而且这个通常取决于开发者决定哪一种 ...

  8. 基于注解配置spring

    1 对 bean 的标注基于注解方式有3个注解 @Component @Repository 对DAO类进行标注 @Service 对Service类进行标注 @Controller  对Contro ...

  9. Spring IOC容器装配Bean_基于注解配置方式

    bean的实例化 1.导入jar包(必不可少的) 2.实例化bean applicationContext.xml(xml的写法) <bean id="userDao" cl ...

随机推荐

  1. SpringBoot管理Banner

    一.引言 在springboot项目启动的时候,会在console控制台中打印出一个SPRING的图案.有时候为了减少日志输出以及控制台的输出,就需要将这些给去除:有时候需要换上个人的标签等标识,就需 ...

  2. sql语句中as的意思是什么?

    as 一般用在两个地方,一个是query的时候,用来重新指定返回的column(列) 名字如:一个table 有个column叫 id, 我们的query是select id from table1. ...

  3. 关于html 中form表单的内标签和使用

    表单标记 1.普通文本框: <input type=”text” name=”名称” value=”值”;不写value默认为空/> 2.密码框:<input type=”passw ...

  4. Zookeeper + Guava loading cache 实现分布式缓存

    1. 概述 项目中,创建的活动内容存入redis,然后需要用到活动内容的地方,从redis去取,然后参与计算. 活动数据的一个特点是更新不频繁.数据量不大.因为项目部署一般是多机器.多实例,除了red ...

  5. 在 Ubuntu上使用 MySQL

    MySQL 安装配置 https://help.ubuntu.com/12.04/serverguide/mysql.html MySQL Manual http://dev.mysql.com/do ...

  6. JS算法之八皇后问题(回溯法)

    八皇后这个经典的算法网上有很多种思路,我学习了之后自己实现了一下,现在大概说说我的思路给大家参考一下,也算记录一下,以免以后自己忘了要重新想一遍. 八皇后问题 八皇后问题,是一个古老而著名的问题,是回 ...

  7. LeetCode 533----Lonely Pixel II

    问题描述 Given a picture consisting of black and white pixels, and a positive integer N, find the number ...

  8. SQL Server中【case...end】的用法

    在SQL Server中 case...end 语句,一般有如下两种用法: 1.相当于C#中if...else,例: select CName,头衔=case when CLevel='A1' the ...

  9. javascript animation lib greensock gsap介绍

    一般前台做动画有以下几种方式: 1. 简单的css transition动画; 2. css animation动画 3. javascript库动画 一般来说css html5动画只适用于简单的形变 ...

  10. visio 修改画布大小

    按住Ctrl,鼠标移到画布边缘,拖拉即可.