Annotation injection is performed before XML injection, thus the latter configuration will override the former for properties wired through both approaches.

Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file. So consider to have following configuration file in case you want to use any annotation in your Spring application.

<?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>

Once <context:annotation-config/> is configured, you can start annotating your code to indicate that Spring should automatically wire values into properties, methods, and constructors. Let us see few important annotations to understand how they work:

  • @Autowired
  • The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.
  • @Required
  • The @Required annotation applies to bean property setter methods.
  • @Qualifier
  • The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.
  • @JSR-250 Annotations
  • Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.

Spring @Required Annotation

Here is the content of Student.java file:

 package com.tutorialspoint;
 import org.springframework.beans.factory.annotation.Required;
 public class Student {
private Integer age;
private String name;

@Required

    public void setAge(Integer age) {
this.age = age;
    }
public Integer getAge() {

return age; }

@Required

    public void setName(String name) {
this.name = name;
    }
public String getName() {

The @Required annotation applies to bean property setter methods and it indicates that the affected bean property must be populated in XML configuration file at configuration time otherwise the container throws a BeanInitializationException exception. Below is an example to show the use of @Required annotation.

Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:

Description

Create a project with a name SpringExample and create a
package com.tutorialspoint under the src folder in the created project.

Add required Spring libraries using Add External JARs option as explained in the Spring
Hello World Example chapter.

Create Java classes Student and MainApp under the com.tutorialspoint package.

Create Beans configuration file Beans.xml under the src folder.

The final step is to create the content of all the Java files and Bean Configuration file and
run the application as explained below.

      return name;
}

}

Following is the content of the MainApp.java file: package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {

ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");

Student student = (Student) context.getBean("student");
System.out.println("Name : " + student.getName() );
System.out.println("Age : " + student.getAge() );

}
}

Following is the content of the configuration file Beans.xml:
<?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/>
   <!-- Definition for student bean -->

<bean id="student" class="com.tutorialspoint.Student"> <property name="name" value="Zara" />

<!-- try without passing age and check the result -->

<!-- property name="age" value="11"-->

   </bean>
</beans>

Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will raise BeanInitializationException exception and print the following error along with other log messages:

Property 'age' is required for bean 'student'

Next, you can try above example after removing comment from 'age' property as follows:

<?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/>
   <!-- Definition for student bean -->

<bean id="student" class="com.tutorialspoint.Student">

<property name="name" value="Zara" />

<property name="age" value="11"/> </bean>

</beans>

Now above example will produce following result:

Name : Zara
Age : 11

Spring @Autowired Annotation

@Autowired on Setter Methods Example

Here is the content of TextEditor.java file:

package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class TextEditor {
private SpellChecker spellChecker;

@Autowired

   public void setSpellChecker( SpellChecker spellChecker ){
this.spellChecker = spellChecker;
   }
public SpellChecker getSpellChecker( ) {
      return spellChecker;
}
   public void spellCheck() {
spellChecker.checkSpelling();

} }

Following is the content of another dependent class file SpellChecker.java: package com.tutorialspoint;

public class SpellChecker {
public SpellChecker(){

System.out.println("Inside SpellChecker constructor." ); }

public void checkSpelling(){ System.out.println("Inside checkSpelling." );

} }

Following is the content of the MainApp.java file: package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}

Following is the configuration file Beans.xml:

<?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/>
<!-- Definition for textEditor bean without constructor-arg  -->

<bean id="textEditor" class="com.tutorialspoint.TextEditor"> </bean>

  <!-- Definition for spellChecker bean -->

<bean id="spellChecker"class="com.tutorialspoint.SpellChecker"> </bean>

</beans>

Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:

Inside SpellChecker constructor.
Inside checkSpelling.

@Autowired with (required=false) option

By default, the @Autowired annotation implies the dependency is required similar to @Required annotation, however, you can turn off the default behavior by using (required=false) option with @Autowired.

The following example will work even if you do not pass any value for age property but still it will

demand for name property. You can try this example yourself because this is similar to @Required annotation example except that only Student.java file has been changed.

package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class Student {
private Integer age;
private String name;

@Autowired(required=false) public void setAge(Integer age) {

   this.age = age;
}
public Integer getAge() {
return age;

}

@Autowired

public void setName(String name) {
this.name = name;
}
public String getName() {
   return name;
}

}

Spring @Qualifier Annotation

 

Example

Here is the content of Student.java file:

package com.tutorialspoint;

public class Student {

private Integer age;

private String name;

public void setAge(Integer age) {

this.age = age;

}

public Integer getAge() {

return age; }

public void setName(String name) {

this.name = name;

}

public String getName() {

return name;

} }

Here is the content of Profile.java file: package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

public class Profile {

@Autowired

@Qualifier("student1") private Student student;

public Profile(){
System.out.println("Inside Profile constructor." );

}

public void printAge() {
System.out.println("Age : " + student.getAge() );

}

public void printName() {
System.out.println("Name : " + student.getName() );

} }

Following is the content of the MainApp.java file: package com.tutorialspoint;

import org.springframework.context.ApplicationContext;

import

org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

public static void main(String[] args) {

ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");

Profile profile = (Profile) context.getBean("profile");

profile.printAge();

profile.printName();

}

}

Consider the example of following configuration file Beans.xml: <?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/>

<!-- Definition for profile bean -->

<bean id="profile" class="com.tutorialspoint.Profile"> </bean>

<!-- Definition for student1 bean -->

<bean id="student1" class="com.tutorialspoint.Student">

<property name="name" value="Zara" />

<property name="age" value="11"/> </bean>

<!-- Definition for student2 bean -->

<bean id="student2" class="com.tutorialspoint.Student"> <property name="name" value="Nuha" />
<property name="age" value="2"/>

</bean>

</beans>

Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:

Inside Profile constructor.

Age : 11

Name : Zara

@Resource Annotation

You can use @Resource annotation on fields or setter methods and it works the same as in Java EE 5. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it followsby-nameautowiring semantics as demonstrated in the below example:

package com.tutorialspoint;
import javax.annotation.Resource;
public class TextEditor {
private SpellChecker spellChecker;

@Resource(name= "spellChecker")
public void setSpellChecker( SpellChecker spellChecker ){

      this.spellChecker = spellChecker;
}
   public SpellChecker getSpellChecker(){
return spellChecker;
   }
public void spellCheck(){
      spellChecker.checkSpelling();

TUTORIALS POINT

Simply Easy Learning Page 78

} }

If no 'name' is specified explicitly, the default name is derived from the field name or setter method. In case of a field, it takes the field name; in case of a setter method, it takes the bean property name.

[转载]Spring Annotation Based Configuration的更多相关文章

  1. [转载]Spring Java Based Configuration

    @Configuration & @Bean Annotations Annotating a class with the @Configuration indicates that the ...

  2. spring Annotation based configuration

    spring 注解相关 https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s11.html

  3. [转] Spring - Java Based Configuration

    PS: Spring boot注解,Configuration是生成一个config对象,@Bean指定对应的函数返回的是Bean对象,相当于XML定义,ConfigurationProperties ...

  4. Spring 3 Java Based Configuration with @Value

    Springsource has released the Javaconfig Framework as a core component of Spring 3.0. There is a tre ...

  5. Spring 4 Ehcache Configuration Example with @Cacheable Annotation

    http://www.concretepage.com/spring-4/spring-4-ehcache-configuration-example-with-cacheable-annotatio ...

  6. An annotation based command line parser

    Java命令行选项解析之Commons-CLI & Args4J & JCommander http://rensanning.iteye.com/blog/2161201 JComm ...

  7. Unit Testing of Spring MVC Controllers: Configuration

    Original Link: http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-m ...

  8. 原创 | 我被面试官给虐懵了,竟然是因为我不懂Spring中的@Configuration

    GitHub 3.7k Star 的Java工程师成神之路 ,不来了解一下吗? GitHub 3.7k Star 的Java工程师成神之路 ,真的不来了解一下吗? GitHub 3.7k Star 的 ...

  9. 我被面试官给虐懵了,竟然是因为我不懂Spring中的@Configuration

    现在大部分的Spring项目都采用了基于注解的配置,采用了@Configuration 替换标签的做法.一行简单的注解就可以解决很多事情.但是,其实每一个注解背后都有很多值得学习和思考的内容.这些思考 ...

随机推荐

  1. zz 如何在Linux下创建与解压zip, tar, tar.gz和tar.bz2文件

    January 2nd, 2009 at 10:31 pm Linux 解压, Linux, tar, tar.bz2, tar.gz, tgz, zip, 压缩, 打包, 文档 这么多年来,数据压缩 ...

  2. Base64加密

    实际开发中可能需要使用到可解密的加密方式,例如客户端记住用户的密码,客户端不能记住明文密码,那就需要对明文密码进行加密,然后在表单提交之后先对密码进行解密,在进行MD5加密和数据库中的密码进行比较实现 ...

  3. jsp探针

    在网上找到一些jsp探针,收藏下. JSP探针1.jsp <%@ page contentType="text/html;charset=gb2312" %> < ...

  4. Nginx+Center OS 7.2 开机启动设置(转载)

    centos 7以上是用Systemd进行系统初始化的,Systemd 是 Linux 系统中最新的初始化系统(init),它主要的设计目标是克服 sysvinit 固有的缺点,提高系统的启动速度.关 ...

  5. sublime text3的配置(整理)

    一.代码片段 开发人员很多时候是在做一些重复的工作. 针对不同数据表的增删改查都差不多,重复来重去的.很久不写程序了,利用十一假期在家看看书,写写程序. 最近一直很喜欢使用Sublime Text,发 ...

  6. phpcms v9 源码解析(4)content模块下的index.php文件的init()方法解析

    在了解index.php中的init函数的时候,让我们先看看最开始的几行代码 1-5  第二行, defined('IN_PHPCMS') or exit('Nopermission resource ...

  7. 在 SQL Server 中的网络数据库文件的支持说明

    其实就是一个学员问SQL Server 是否能存放的于NAS(UAC 的路径下). 官方的回答简略版本为:可以,需要满足一些强制性的硬件要求.但需要考虑一系列的性能的问题. http://suppor ...

  8. linux常用命令收集(持续中)

    mv  :  既可以重命名,又可以移动文件或文件夹 例子:将目录A重命名为B mv A B 例子:将/a目录移动到/b下,并重命名为c mv /a /b/c 其实在文本模式中要重命名文件或目录的话也是 ...

  9. 绘制dot 图

    常用参数 格式:dot -T<type> -o<outfile> <infile.dot> 输入文件是<infile.dot>,生成的格式由<ty ...

  10. 【C#】索引器

    索引器允许类或者结构的实例按照与数组相同的方式进行索引取值,索引器与属性类似,不同的是索引器的访问是带参的. 索引器和数组比较: (1)索引器的索引值(Index)类型不受限制 (2)索引器允许重载 ...