Java framework --- spring dependency injection, java --- spring

Source: Internet
Author: User

Java framework --- spring dependency injection, java --- spring

There are four spring dependency injection methods.

  • Constructor Injection
  • Property Injection
  • Factory Injection
  • Annotation Injection

An example is provided below:

User.java
package com.bjsxt.model;public class User {    private String username;    private String password;    public User(){}    public User(String username, String password) {        super();        this.username = username;        this.password = password;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    @Override    public String toString() {        return "User [username=" + username + ", password=" + password + "]";    }}
UserDAO.java
package com.bjsxt.dao;import com.bjsxt.model.User;public interface UserDAO {    public void save(User user);}
UserDAO implementation class UserDAOImpl
package com.bjsxt.dao.impl;import com.bjsxt.dao.UserDAO;import com.bjsxt.model.User;public class UserDAOImpl implements UserDAO {    public void save(User user) {        //Hibernate        //JDBC        //XML        //NetWork        System.out.println("user saved!");    }}

Factory

First: UserFactory
Package com. bjsxt. factory; import com. bjsxt. model. user; public class UserFactory {public User CreatUser () {User user User = new user (); User. setUsername ("week 1"); user. setPassword ("oumyye"); return user ;}}
Second: UserFactory2
Package com. bjsxt. factory; import com. bjsxt. model. user; public class UserFactory2 {public static User CreatUser () {User user User = new user (); User. setUsername ("my Jesus 1"); user. setPassword ("oumyye"); return user ;}}
Control Layer: UserService
package com.bjsxt.service;import com.bjsxt.dao.UserDAO;import com.bjsxt.model.User;public class UserService {        private UserDAO userDAO;          public void init() {        System.out.println("###########init");    }        public void save(User user) {        userDAO.save(user);    }    public UserDAO getUserDAO() {        return userDAO;    }    public void setUserDAO(UserDAO userDAO) {        this.userDAO = userDAO;    }        public UserService(UserDAO userDAO) {        super();        this.userDAO = userDAO;    }        public void destroy() {        System.out.println("destroy");    }}

Configuration File: bean. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "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"> <! -- Constructor injection --> <bean id = "user" class = "com. bjsxt. model. user "> <constructor-arg index =" 0 "type =" String "value =" zhou "> </constructor-arg> <constructor-arg index =" 1 "type = "String" value = "password"> </constructor-arg> </bean> <! -- Property injection --> <bean id = "user1" class = "com. bjsxt. model. user "> <property name =" username "value =" zhang "> </property> <property name =" password "value =" oumyye "> </property> </bean> <! -- Factory injection --> <bean id = "userFactory" class = "com. bjsxt. factory. userFactory "> </bean> <bean id =" user2 "factory-bean =" userFactory "factory-method =" CreatUser "> </bean> <! -- Static factory injection --> <bean id = "user3" class = "com. bjsxt. factory. userFactory2 "factory-method =" CreatUser "> </bean> <bean id =" u "class =" com. bjsxt. dao. impl. userDAOImpl "> </bean> <bean id =" userService "class =" com. bjsxt. service. userService "init-method =" init "destroy-method =" destroy "scope =" prototype "> <! -- <Property name = "userDAO" ref = "u"/> --> <! -- Constructor-arg> <ref bean = "u"/> </constructor-arg> </bean> </beans>

Test class:

Package com. bjsxt. service; import static org. junit. assert. *; import org. junit. test; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext; import com. bjsxt. model. user; public class UserServiceTest {@ Test public void test () {ApplicationContext applicationContext = new ClassPathXmlApplicationContext ("beans. xml "); UserService userService = (UserService) applicationContext. getBean ("userService"); // constructor injects User user User = (User) applicationContext. getBean ("user"); // property injection User user1 = (User) applicationContext. getBean ("user1"); // The factory injects User user2 = (User) applicationContext. getBean ("user2"); // The factory injects User 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 ();}}

Result:

########## InitUser [username = zhou, password = password] User [username = zhang, password = oumyye] User [username = week 1, password = oumyye] User [username = even my Jesus 1, password = oumyye] user saved! Destroy

The annotation method is described in detail later.

Dependency injection-automatic assembly

Spring provides a mechanism for automatic assembly of dependent objects. However, automatic assembly is not recommended in actual applications because automatic assembly will produce unknown conditions and developers cannot predict the final assembly results.

Automatic Assembly is implemented in the configuration file as follows:

<Bean id = "***" class = "***" autowire = "byType">

You only need to configure an autowire attribute to complete automatic assembly without writing <property> in the configuration file. However, you still need to generate the setter method of the dependent object in the class.

The Autowire attribute values include the following:

· ByType can be assembled by type to search for beans of this type in the container Based on the attribute type. If there are multiple beans, an exception is thrown. If no bean of this type is found, the attribute value is null;

· ByName assembly by name: You can query beans with the same name in the container based on the property name. If no bean name is found, the property value is null;

· The constructor and byType methods are similar. The difference is that they are applied to the constructor parameters. If the bean of the same type as the constructor parameter is not found in the container, an exception is thrown;

· Autodetect determines whether to use constructor or byType for automatic assembly through the introspection mechanism of bean classes. If the default constructor is found, byType is used.

Related Article

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.