Spring Summary four: IOC and Di annotation methods

Source: Internet
Author: User

First we want to understand the differences between annotations and XML configuration:

, but the annotations are written on top of the bean instead of the bean configuration we made in the XML file before, that is, we use annotations in a way that does not have to be configured in XML, which is relatively easy to annotate.

IOC gets the object annotation method:

On the basis of our second (IOC container configuration XML) Summary, make the changes:

First of all, our applicationcontext.xml configuration file is slightly modified: (add beans with green background)

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans" xmlns:context= "Http://www.springframework.org/schema/context" Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans /spring-beans.xsd Http://www.springframework.org/schema/context Http://www.springframework . org/schema/context/spring-context.xsd">    <!--Open Scan Scan package Com.zy the following - <Context:component-scan  base-package= "Com.zy"></  Context:component-scan>     </Beans>

Then our JavaBean class plus annotations (Component):

@Component ("Bean1")publicclass  Bean1 {    public  Bean1 () {        System.out.println ("Bean1 method of construction without parameters");}    }

This replaces what we previously configured in Applicationcontext.xml: <bean id= "Bean1" class= "Com.zy.IoC.Bean1" ></bean>

Test and operation results please refer to the summary of the second article, the results are the same.

The Spring container also provides a @component equivalent of three derivative annotations

    • @Repository for registering DAO (persistence layer)

    • @Service for registering service (business tier)

    • @Controller for registering an Action (presentation layer)

Take @repository as an example:

/*** Test Userdao interface*/ Public InterfaceUserdao { Public voidgetUser ();}/*** Userdao Implementation Class 1*/@Repository ("Userdao") Public classUserdaoimplImplementsUserdao { PublicUserdaoimpl () {System.out.println ("Dao1 Construction Method"); } @Override Public voidGetUser () {System.out.println ("Userdao implementation Class 1 Get user information ..."); }}

Test:

    @Test    publicvoidthrows  Exception {        / /  Get Spring container        new classpathxmlapplicationcontext ("Applicationcontext.xml") according to the spring configuration file;         // Use the container to create the Userdao implementation class object  Userdao and the Bean's ID in the configuration file is consistent        Userdao dao = Ac.getbean (" Userdao ", Userdao. class );        Dao.getuser ();    }

Operation Result:

DI Dependency Injection notation:

annotation Base type properties : This is not much of an introduction.

// The base Type property @Value ("#{' Jacky '}")private String name;

Annotation Complex Type properties:

1,SPRING3.0 provides @value annotations

    // Complex Type Properties     // The first @Value combined with Spel    @Value ("#{userdao}")    private Userdao Userdao;

2,SPRING2.0 provides @autowired annotations combined with @Qualifier annotations

    // second @Autowired annotations combined with @Qualifier annotations     // If you use @autowired by default by type injection, if there are multiple of the same type    you can only find a single // use @Qualifier to inject by name     @Autowired    @Qualifier ("Userdao")    private Userdao Userdao;

3,JSR-250 specification provides @Resource annotation implementation injection (deprecated)

    // The third type of JSR-250 provides    @resource annotations // do not write the Name property, inject by type, write the Name property, inject    by name @Resource (name = "Userdao")    private Userdao Userdao;

To inject Userdao into UserService as an example:

JavaBean Code:

/*** Test Userdao interface*/ Public InterfaceUserdao { Public voidgetUser ();}/*** Userdao Implementation Class 1*/@Repository ("Userdao") Public classUserdaoimplImplementsUserdao {@Override Public voidGetUser () {System.out.println ("2 Userdao Implementation Class 1 Get user information ..."); }}/*** UserService Interface*/ Public InterfaceUserService { Public voidgetUser ();}/*** UserService Implementation class*/@Service ("UserService") Public classUserserviceimplImplementsUserService {//@[email protected] the way//@Autowired//@Qualifier ("Userdao")//@Value ("#{}") using annotation injection in a way that is consistent with the annotation of the DAO implementation class    PrivateUserdao Userdao; @Override Public voidGetUser () {System.out.println ("1 Business Layer 1 Get User Object ...");    Userdao.getuser (); }}

Test:

    @Test    publicvoidthrows  Exception {        new Classpathxmlapplicationcontext ("Applicationcontext.xml");         = Ac.getbean ("UserService", UserService.  Class);        Userservice.getuser ();    }

Operation Result:

Use of other annotations:

Life cycle Annotations:

@PostConstruct Initialization method

@PreDestroy Method of Destruction

//Note for Beans@Component ("Springlifecycle") Public classspringlifecycle {//Construction Method     Publicspringlifecycle () {System.out.println ("Springlifecycle Construction ..."); }    //annotations for initialization methods@PostConstruct Public voidinit () {System.out.println ("Springlifecycle initialization ..."); }    //annotations for Destruction methods@PreDestroy Public voiddestroy () {System.out.println ("Springlifecycle destruction ..."); }     Public voidhellospring () {System.out.println ("Hello Spring!"); }}

Test:

    @Test    publicvoid  testlifecycle () {        new  Classpathxmlapplicationcontext (                "Applicationcontext.xml");         = (springlifecycle) ac.getbean ("Springlifecycle");        Springlifecycle.hellospring ();         // Call Close (ApplicationContext does not have a close method, requires the rotor class to call Close)        Classpathxmlapplicationcontext Classac = (Classpathxmlapplicationcontext) AC;        Classac.close ();    }

Operation Result:

Scope Annotations for Beans:

or the JavaBean class above:

// The bean annotation @Component ("springlifecycle")// Scope annotation prototype is a multi-instance, the default is singleton single instance @ Scope ("prototype")publicclass Springlifecycle {

Test:

@Test Public voidTestscope ()throwsException {applicationcontext ApplicationContext=NewClasspathxmlapplicationcontext ("Applicationcontext.xml"); Springlifecycle LifeCycleBean1=(springlifecycle) applicationcontext. Getbean ("Springlifecycle"); Springlifecycle lifeCycleBean2=(springlifecycle) applicationcontext. Getbean ("Springlifecycle");        System.out.println (LIFECYCLEBEAN1);        System.out.println (LIFECYCLEBEAN2); //calling the Close method from reflection codeMethod CloseMethod = Applicationcontext.getclass (). GetMethod ("Close");    Closemethod.invoke (ApplicationContext); }

Operation Result:

You will find that the destruction method does not work, it is explained that theBean must be singleton single instance when the destruction method can be executed.

Set scope to Singleton:

// The Bean's annotation @Component ("springlifecycle")// scope annotation, singleton as the default value, can not write this annotation @Scope (" Singleton ")publicclass Springlifecycle {

Execution Result:

Spring Summary four: IOC and Di annotation methods

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.