Java Framework---Spring dependency injection

Source: Internet
Author: User

There are 4 ways that spring relies on injection

    • Construct Method Injection
    • Attribute Injection
    • Factory injection
    • Annotation Injection

The following is an example of a unified explanation:

User.java
 PackageCom.bjsxt.model; Public classUser {PrivateString username; PrivateString password;  PublicUser () {} PublicUser (string Username, string password) {Super();  This. Username =username;  This. Password =password; }     PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; } @Override PublicString toString () {return"User [username=" + Username + ", password=" + password + "]"; }}
Userdao.java
 Package Com.bjsxt.dao; Import Com.bjsxt.model.User;  Public Interface Userdao {    publicvoid  Save (user user);}
Userdao Implementation Class Userdaoimpl
 PackageCom.bjsxt.dao.impl;ImportCom.bjsxt.dao.UserDAO;ImportCom.bjsxt.model.User; Public classUserdaoimplImplementsUserdao { Public voidSave (User user) {//Hibernate//JDBC//XML//NetWorkSystem.out.println ("User saved!"); }}

Factory class

First one: userfactory
 Package com.bjsxt.factory; Import Com.bjsxt.model.User;  Public class userfactory {    public  user Creatuser () {        user user=new  User ();        User.setusername ("Week 1");        User.setpassword ("Oumyye");         return user;    }}
 Package com.bjsxt.factory; Import Com.bjsxt.model.User;  Public class UserFactory2 {    publicstatic  user Creatuser () {        user user=new  User ();        User.setusername ("Even my Yes 1");        User.setpassword ("Oumyye");         return user;    }}
Control layer: UserService
 PackageCom.bjsxt.service;ImportCom.bjsxt.dao.UserDAO;ImportCom.bjsxt.model.User; Public classUserService {PrivateUserdao Userdao;  Public voidinit () {System.out.println ("########## #init"); }         Public voidSave (User user) {userdao.save (user); }     PublicUserdao Getuserdao () {returnUserdao; }     Public voidSetuserdao (Userdao Userdao) { This. Userdao =Userdao; }         PublicUserService (Userdao Userdao) {Super();  This. Userdao =Userdao; }         Public voiddestroy () {System.out.println ("Destroy"); }}

Configuration file: Bean.xml

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"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-2.5. XSD ">    <!--Construct method Injection -    <BeanID= "User"class= "Com.bjsxt.model.User" >    <Constructor-argIndex= "0"type= "String"value= "Zhou"></Constructor-arg>    <Constructor-argIndex= "1"type= "String"value= "Password"></Constructor-arg>    </Bean>        <!--Attribute Injection -    <BeanID= "User1"class= "Com.bjsxt.model.User" >    < Propertyname= "username"value= "Zhang"></ Property>    < Propertyname= "Password"value= "Oumyye"></ Property>    </Bean>    <!--Factory Injection -    <BeanID= "Userfactory"class= "Com.bjsxt.factory.UserFactory" > </Bean>    <BeanID= "User2"Factory-bean= "Userfactory"Factory-method= "Creatuser"></Bean>        <!--Static Factory injection -    <BeanID= "User3"class= "Com.bjsxt.factory.UserFactory2"Factory-method= "Creatuser"> </Bean>          <BeanID= "U"class= "Com.bjsxt.dao.impl.UserDAOImpl"></Bean>           <BeanID= "UserService"class= "Com.bjsxt.service.UserService"Init-method= "Init"Destroy-method= "Destroy"Scope= "Prototype">            <!--<property name= "Userdao" ref= "U"/> -      <!--Construct method Injection -       <Constructor-arg>           <refBean= "U"/>       </Constructor-arg>  </Bean>  </Beans>

Test class:

 PackageCom.bjsxt.service;Import Staticorg.junit.assert.*;Importorg.junit.Test;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;ImportCom.bjsxt.model.User; Public classuserservicetest {@Test Public voidTest () {ApplicationContext ApplicationContext=NewClasspathxmlapplicationcontext ("Beans.xml"); UserService UserService= (UserService) applicationcontext.getbean ("UserService"); //Construct method InjectionUser user= (user) Applicationcontext.getbean ("User"); //Attribute InjectionUser user1= (user) Applicationcontext.getbean ("user1")); //Factory InjectionUser user2= (user) Applicationcontext.getbean ("User2")); //Factory InjectionUser user3= (user) Applicationcontext.getbean ("User3"));        SYSTEM.OUT.PRINTLN (user);        System.out.println (user1);        System.out.println (User2);        System.out.println (USER3);        Userservice.save (user);    Userservice.destroy (); }}

Results:

########## #initUser [username=zhou, password=password]user [username=zhang, password=Oumyye] User [Username= Week 1, password=oumyye]user [Username= Even my yes 1, password=oumyye]user saved! Destroy

The annotation method is described in detail later

Dependency Injection-Automatic assembly

Spring provides a mechanism for automating the assembly of dependent objects, but it is not recommended to use automatic assembly in practical applications, because automatic assembly creates an unknown situation and the developer cannot foresee the final assembly result.

Automatic assembly is implemented in the configuration file, as follows:

<bean id= "* * *" class= "* * *" autowire= "Bytype" >

You only need to configure one Autowire property to complete the automatic assembly, no more write <property> in the configuration file, but in the class you want to build the setter method of the dependent object.

The Autowire property values are as follows:

· Bytype assembly by type you can find the type-matching bean in the container based on the property type, if there are more than one, an exception is thrown, and if not found, the property value is null;

· ByName by name the bean with the same property name can be queried in the container based on the name of the property, and if not found, the property value is null;

· constructor is similar to the bytype approach, where it is applied to the constructor parameter, and throws an exception if no bean is found in the container that matches the constructor parameter type.

· AutoDetect uses the Bean class's introspection mechanism (introspection) to determine whether to automate assembly using constructor or Bytype. If you find the default constructor, you will use the Bytype method.

Java Framework---Spring dependency injection

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.