springspring Annotation Injection

Source: Internet
Author: User
I. Spring component scanning mechanism

Spring can automatically scan the classes identified by certain annotations under classpath and put them in the IOC container, using the same XML configuration, but much more efficiently.
There are several (more than one) of the specific components:
1. autowired is auto-injected and automatically finds the right bean from the spring context to inject
2. Resource used to specify name injection
3. Qualifier and autowired with the name of the bean specified
4. Service,controller,repository The class is the Service layer class, Controller layer class, data storage layer class, Spring scan annotation configuration, these classes will be marked to generate beans.
5. Component is a generic, tag class is a component that, when spring scans annotation configurations, flags these classes to generate beans.
(detailed reference for each annotation: Spring Framework Annotation learning)
The above autowired and resource are used to modify the field, constructor, or set method, and do inject. Instead, Service,controller,repository,component is used to modify classes to mark these classes to generate beans. Two. See the use of Spring annotation injection with the example project.

Start by creating a new Maven project and adding spring-related dependencies to the POM.
Then create a new Cardao class and add a @repository annotation to it, as follows:

Package cn.outofmemory.helloannotation;
Import org.springframework.stereotype.Repository;
@Repository public
class Cardao {public
    void Insertcar (string car) {
        string insertmsg = String.Format (" Inserting car%s ", car);
        System.out.println (insertmsg);
    }
}

Create a new Carservice class, annotate the class with @service annotations, define Cardao fields in the class, and decorate the field with autowired, so that an instance of the Cardao class defined above is automatically injected into the Carservice instance.

Package cn.outofmemory.helloannotation;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.stereotype.Service;
@Service public
class Carservice {
    @Autowired
    private Cardao Cardao;
    public void Addcar (String car) {
        this.carDao.insertCar (car);
    }
}

Note: The autowired annotation has a nullable property required, which can be used to specify whether the field is required and, if required, throws an exception if an appropriate instance injection is not found.
Here we use the note injection in App.java with the above test:

Package cn.outofmemory.helloannotation;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {public
    static void Main (string[] args)
    {
        ApplicationContext appContext = new Annotationco Nfigapplicationcontext ("Cn.outofmemory.helloannotation");
        Carservice service = Appcontext.getbean (carservice.class);
        Service.addcar ("BMW");
    }
}

In the main method above we first initialized the Appcontext, which is Annotationconfigapplicationcontext, whose constructor accepts the name of a package to qualify the package to be scanned. You can then get an example of Carservice using the Appcontext Getbean method.
The above example is very simple, the simple use of annotationconfigapplicationcontext, but in the actual project is often not so simple, still need the spring configuration file. The following configuration allows spring to automatically scan the annotation configuration in the spring configuration file.

<!--bean annotation driven-
    <context:annotation-config/>
    <context:component-scan Base-package= "Cn.outofmemory.helloannotation" >
    </context:component-scan>

Let's take a look at a mix of spring configurations and annotations, first adding source folder,src/main/resources to the project and adding Spring.xml, with the following content:

<?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 "> <!--bean annotation driven---< Context:annotation-config/> <context:component-scan base-package= "Cn.outofmemory.helloannotation" > < /context:component-scan> <bean id= "Sqlitecardao" class= "Cn.outofmemory.helloannotation.CarDao" > < Constructor-arg name= "Driver" value= "SQLite"/> </bean> </beans> 

In the above configuration file, we specify to scan the annotation injection through the context:annotation-config and CONTEXT:COMPONENT-SACN nodes, and then we define a bean with ID sqlitecardao. The driver value of its constructor is SQLite.
We modified the next App.java to use the XML config file, and then run the next app to see what happens.

Package cn.outofmemory.helloannotation;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.annotation.AnnotationConfigApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {public
    static void Main (string[] args)
    {
        //applicationcontext appContext = new Annotation Configapplicationcontext ("Cn.outofmemory.helloannotation");
        ApplicationContext appContext = new Classpathxmlapplicationcontext ("/spring.xml");
        Carservice service = Appcontext.getbean (carservice.class);
        Service.addcar ("BMW");
    }
}

Run the program to discover that the output is: inserting car bmw into MySQL, apparently carservice auto-injected Cardao uses the default constructor constructed by the instance. Is it possible to specify by annotations the Sqlitecardao configured in Spring.xml.
We can modify the next Carservice class to specify the name of the bean to use by qualifier annotations.
As below, specify the name of the bean when specifying the autowired annotation, specifying the qualifier annotation at the same time

    @Autowired
    @Qualifier ("Sqlitecardao")
    private Cardao Cardao;

Rerun the next App.java this output is inserting car BMW into SQLite, this time using the bean configured in Spring.xml.
At the beginning of this article we also mention the resouce annotation, which can specify the name injection, and we modify the next Carservice class again:

@Resource (name= "Sqlitecardao") 
private Cardao Cardao;

The effect of Javax.annotation.Resource annotation implementation is the same as the effect of @autowired+ @Qualifier.

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.