Several ways of attribute injection in spring and injection of complex attributes __spring

Source: Internet
Author: User
Tags stringbuffer

In the spring framework, there are several ways in which attributes can be injected, which can be injected through the set method, or injected through the P namespace, in a variety of ways, for complex data types such as objects, arrays, list sets, map sets, properties, etc. , we all have a corresponding injection method.
OK, then let's take a look at so many different injections. three types of property injection methods Construction Method Injection

Construction method injection and P namespace injection we don't use much in development, but we need to see how the constructor is injected first.
Suppose I have a User4, as follows:

public class User4 {
    private String username;

    Public User4 (String username) {
        this.username = username;
    }

    @Override public
    String toString () {return
        "user4{" +
                "username= '" + username + ' \ ' +
                '} ';
    }
}

One of the variables in User4 is called username, and I want to inject a value into it by constructing a method, so I provide the corresponding construction method in User4, and then configure the following in the spring configuration file:

<bean id= "User4" class= "Org.sang.User4" >
        <constructor-arg name= "username" value= "john"/>
    </ Bean>

So I succeeded in assigning value to username.
Let's take a look at the test methods:

    @Test public
    void Test4 () {
        ApplicationContext context = new Classpathxmlapplicationcontext (" Applicationcontext.xml ");
        User4 user = (User4) context.getbean ("User4");
        SYSTEM.OUT.PRINTLN (user);
    }

The test results are as follows:
Set Method Injection

Set method injection is one of the more injection methods we use, and the injection method is also very simple, assuming I have a User5, as follows:

public class User5 {
    private String username;

    public void Setusername (String username) {
        this.username = username;
    }

    @Override public
    String toString () {return
        "user5{" +
                "username= '" + username + ' \ ' +
                '} ';
    }
}

There are also username attributes in User5, but I do not want to inject through the constructor method and want to inject through the set method, so in USER5 we first provide the set method and then configure it in the spring configuration file as follows:

<bean id= "User5" class= "Org.sang.User5" >
        <property name= "username" value= "Lisi"/>
    </bean >

The test code is as follows:

    @Test public
    void Test5 () {
        ApplicationContext context = new Classpathxmlapplicationcontext (" Applicationcontext.xml ");
        User5 user = (USER5) context.getbean ("User5");
        SYSTEM.OUT.PRINTLN (user);
    }

The test results are as follows:
p Namespace Injection

P namespace injection is also a way to inject, although not much, let's look at how the P namespace is injected.
First, we need to add the P namespace in the bean node of the spring configuration, as follows:

<beans xmlns= "Http://www.springframework.org/schema/beans"
       xmlns:p= "http://www.springframework.org/ schema/p "
       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 ">

Now suppose I have a User6, as follows:

public class User6 {
    private String username;

    public void Setusername (String username) {
        this.username = username;
    }
    public void Test () {
        System.out.println (username);
    }
}

There is a username attribute in User6, and I provide the set method for this property, and we'll see how to inject it through the P namespace in the configuration file:

<bean id= "User6" class= "Org.sang.User6" P:username= "John" >

Execute the corresponding value directly in the Bean node by P:username. It's also a way to inject, but we don't use much of it in development. injection of complex attributes

The above cases we are talking about are very simple attributes, in the actual development of the properties we encounter may look different, such as the following. Injection of Objects

This is the most commonly used injection in development. To give a common usage scenario, we operate the database at the DAO layer and do business logic operations at the service level, so I need to have a DAO instance in service, as follows, I have a userdao:

public class Userdao {public
    void GetData () {
        System.out.println ("Get Data!");
    }

I also have a userservice:

public class UserService {
    private Userdao Userdao;

    public void Setuserdao (Userdao userdao) {
        This.userdao = Userdao;
    }

Public    UserService (Userdao userdao) {
//        This.userdao = Userdao;    public

    void GetData () {
        userdao.getdata ();
    }
}

There is an instance of Userdao in UserService, and I've provided a set method that will be injected through the set method, and we'll see how to write in the spring configuration file:

<bean id= "Userdao" class= "Org.sang.UserDao"/> <bean id= "
    userservice" class= "Org.sang.UserService" >
        <property name= "Userdao" ref= "Userdao"/>
        <!--<constructor-arg name= "Userdao" ref= " Userdao "/>-->
    </bean>

We want to configure two beans, the first bean is used to configure a Userdao instance, the second bean is used to configure a UserService instance, and when the UserService instance is fetched, the Userdao that the first bean gets is passed as a parameter.
Of course, we can also use the construction method to inject the object, the way I commented out of the code, I do not repeat here. Array injection &list set injection &MAP injection &properties Injection

Injection of these complex properties I put it together, suppose I had a User7, as follows:

public class User7 {private string[] names;
    Private list<string> List;
    Private map<string, string> Map;

    private properties Properties;
    public void Setnames (string[] names) {this.names = names;
    public void setlist (list<string> list) {this.list = list;
    public void Setmap (map<string, string> map) {this.map = Map;
    public void SetProperties (properties properties) {This.properties = properties;
        public void Test () {StringBuffer sb1 = new StringBuffer ();
        for (String name:names) {sb1.append (name). Append (",");
        } stringbuffer SB2 = new StringBuffer ();
        for (String s:list) {sb2.append (s). Append (",");
        } stringbuffer SB3 = new StringBuffer ();
        Set<string> keyset = Map.keyset (); for (String s:keyset) {sb3.append ("key: + S +"; Value: "+ map.get (s)). Append (",");
        } System.out.println (Sb1.tostring ());
        System.out.println (Sb2.tostring ());
        System.out.println (Sb3.tostring ());
    System.out.println (Properties.getproperty ("username")); }
}

User7 has included these complex properties, let's take a look at how to inject values into the spring's configuration file:

<bean id= "User7" class= "Org.sang.User7" > <property name= "names" > <list> <value> John </value> <value> Dick </value> <value> Harry </value&
            Gt </list> </property> <property name= "List" > <list> <
            Value> Football </value> <value> basketball </value> <value> Table tennis </value>
                </list> </property> <property name= "Map" > <map> <entry key= "username" value= "john"/> <entry key= "password" value= "123456"/> < /map> </property> <property name= "Properties" > <props> &L T;prop key= "username" > Zhao Liu </prop> </props> </property> </bean>

The small partners see that the array and list collection are injected in the same way. Because the map is stored as a key-value pair, the injection is slightly different.

OK, above.

This case downloads:

This case GitHub address https://github.com/lenve/JavaEETest/tree/master/Test28-Spring1

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.