Spring-dependent injection in--java project using spring annotation method

Source: Internet
Author: User
annotation injection, as the name implies, implements injection through annotations, and the common annotations associated with spring and injection are autowired, Resource, Qualifier, Service, Controller, Repository, and Component.
Autowired is an automatic injection that automatically finds the appropriate bean from the spring context to inject resource to specify name Injection qualifier and autowired, specifying the name of the Bean Service,controller, Repository tags classes are service layer classes, controller class, data storage layer classes, Spring scan annotation configuration, these classes are marked to generate beans. component is a generic, tag class is a component, and spring scans the annotation configuration to mark these classes to generate beans.

The autowired and resource above are used to modify fields, constructors, or set methods and to inject them. Service,controller,repository,component, however, is used to decorate the class, marking these classes to generate beans.

MAVEN's Pom.xml

<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> < Org.springframework.version>3.1.1.release</org.springframework.version> </properties> < dependencies> <dependency> <groupId>junit</groupId> <artifactid>junit</artif
    
    actid> <version>4.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactid>spring-webmvc</arti
	    factid> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version >${org.springframework.version}</version> </dependency> <dependency> <groupId> Org.springframework</groupid> <artifactid&Gt;spring-test</artifactid> <version>${org.springframework.version}</version> <type>jar& lt;/type> <scope>test</scope> </dependency> <dependency> &LT;GROUPID&GT;ORG.ASPECTJ </groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.2</version> </d ependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId> jackson-core</artifactid> <version>2.2.3</version> </dependency> <dependency> < Groupid>com.fasterxml.jackson.core</groupid> <artifactId>jackson-databind</artifactId> < version>2.2.3</version> </dependency> <dependency> <groupid>com.fasterxml.jackson.core
	</groupId> <artifactId>jackson-annotations</artifactId> <version>2.2.3</version> </dependency> </dependencies>

1, create DAO layer, add @repository annotation to it (note: DAO class does not need to implement an interface, of course, implement interface also can)

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);
    }


2, service layer, @Service annotation, define Cardao fields in this class, and decorate this field by autowired, so that an instance of the Cardao class defined above is automatically injected into the Carservice instance. (Note: Service class does not need to implement an interface, of course, implement interface can also)

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);
    }
}

3, below we use the above test annotation injection in the App.java:

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 Annotationconfiga Pplicationcontext ("Cn.outofmemory.helloannotation");
        Carservice service = Appcontext.getbean (carservice.class);
        Service.addcar ("BMW");
    }

In the main method above we first initialize the Appcontext, which is Annotationconfigapplicationcontext, and its constructor takes a package name to qualify the package to be scanned. Then we can get the Carservice instance through the Appcontext Getbean method.


The example above is simple enough to use annotationconfigapplicationcontext, but it is often not so simple in actual projects, or it needs a spring configuration file. The spring configuration file also allows spring to automatically scan the annotation configuration with the following configuration.

4. Applicationcontext.xml configuration file (put the file under Classpath)

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


5. Test class:

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 annotationconf Igapplicationcontext ("Cn.outofmemory.helloannotation");
<span style= "White-space:pre" >	string[] fileUrl = new string[]{"Classpath*:applicationcontext.xml"}; </span>
        ApplicationContext appcontext = new Classpathxmlapplicationcontext (FILEURL) <span style= " Font-family: ' Comic Sans MS '; >;</span>
        Carservice service = Appcontext.getbean (carservice.class);
        Service.addcar ("BMW");
    }

Note: The spring fetch bean can be obtained by type, name, or by type, and can be obtained in the following way

Carservice service = (carservice) appcontext.getbean ("Carservice");
The specification of the name for the hump


Reference: Http://outofmemory.cn/code-snippet/3670/spring-inject-by-annotation

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.