Annotation-based Spring Configuration

Source: Internet
Author: User

1. Use @ autowired for automatic Injection

Spring uses the @ autowired annotation to implement bean dependency injection. Let's look at an example:

1. Inject class attributes

<Bean id = "car1" class = "Spring. IOC. demo1.car "Scope =" Singleton "P: Brand =" Spring injection-Hongqi 001 "P: color =" Spring injection-purple "P: maxspeed =" 520 "/> <! -- Instantiate through annotation --> <bean id = "useautowired" class = "Spring. IOC. autowired. useautowired"/>
package spring.ioc.autowired;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import spring.ioc.demo1.Car;public class UseAutoWired {        @Autowired    @Qualifier("car1")    private Car car;        public String toString(){        return car.toString();    }}
public static void main(String[] args) {                ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");                UseAutoWired useAutoWired = ctx.getBean("useAutoWired",UseAutoWired.class);        System.out.println(useAutoWired);            }

Output: The car is: Spring injection-Hongqi 001, color is: Spring injection-purple, maxspeed is: 520

Note: @ autowired searches for matched beans in the container by type matching by default. When there is only one matching bean, spring injects it into the variable marked by @ autowired.

If the container does not contain a bean that matches the annotation variable type, nosuchbeandefinitionexception is thrown. If you do not want to throw an exception:

Use @ autowired (request = false) for annotation.

In the above example, if the container contains more than one matching carbean, we need to use @ qualifier to specify the name of the injected bean.

If no name is specified, the following error occurs: Expected single matching bean but found.

 

2. Inject class methods

<! -- Inject methods with annotations --> <bean id = "useautowiredmethod" class = "Spring. IOC. autowired. useautowiredmethod"/>
package spring.ioc.autowired;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import spring.ioc.demo1.Car;public class UseAutoWiredMethod {        private Car car1;        @Autowired    @Qualifier("car1")    public void getInfo(Car car1){        this.car1 = car1;    }        public String toString(){        return car1.toString();    }}
Public static void main (string [] ARGs) {applicationcontext CTX = new classpathxmlapplicationcontext ("classpath: applicationcontext. XML "); // use annotations to inject useautowiredmethod = CTX. getbean ("useautowiredmethod", useautowiredmethod. class); system. out. println (useautowiredmethod );}

Output: The car is: Spring injection-Hongqi 001, color is: Spring injection-purple, maxspeed is: 520

In addition, spring supports annotation of @ qualifier for method parameters to specify the name of the injected Bean:

  @Autowired    //@Qualifier("car1")    public void getInfo(@Qualifier("car1")Car car1){        this.car1 = car1;    }

Summary:

@ Autowired inject bean by type matching by default;

@ Resource: inject bean by name;

@ Inject and @ autowired inject beans by type, but they do not have the required attribute.

 

Ii. View bean scope and life process methods through annotations

Spring provides a @ scope annotation for the annotation configuration. It can be used to display the specified bean scope;

Package spring. IOC. autowired; import Org. springframework. context. annotation. scope; import Org. springframework. stereotype. component; @ component @ scope ("prototype") // polymorphism beanpublic class student {}
Package spring. IOC. autowired; import javax. annotation. postconstruct; import javax. annotation. predestroy; import Org. springframework. beans. factory. annotation. autowired; import Org. springframework. stereotype. component; @ component public class teacher {private student; public teacher () {system. out. println ("execute the constructor... ");} public student getstudent () {return student;} @ autowired public void setstudent (Student) {This. student = student;} @ postconstruct // equivalent to configuring init-method public void init1 () {system. out. println ("executing the init1 method");} @ postconstruct public void init2 () {system. out. println ("executing the init1 method") ;}@ predestroy // equivalent to configuring destroy-method public void destroy1 () {system. out. println ("Run the destroy1 method");} @ predestroy public void destroy2s () {system. out. println ("executing the destroy2 method ");}}
Public static void main (string [] ARGs) {applicationcontext CTX = new classpathxmlapplicationcontext ("classpath: applicationcontext. XML "); // annotation to observe the bean lifecycle (classpathxmlapplicationcontext) CTX ). destroy ();}

Output:

Execute the constructor...
Execute the init1 Method
Execute the init1 Method

Execute the destroy1 Method

Execute the destroy2 Method

When the spring container is used, the bean of The Singleton is automatically instantiated, And the destroy method is called to destroy the bean lifecycle.

We can see that bean is not configured in bean. XML, because we use the @ component annotation, which is equivalent to the following defined content in bean. xml:

<! -- Observe bean lifecycle through annotation --> <bean id = "student" class = "Spring. IOC. autowired. student "/> <bean id =" teacher "class =" Spring. IOC. autowired. teacher "/>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.