Spring dependency Configuration
Through the above learning, the concepts of spring containers and DI should be clearer. DI (dependency injection) is the core of spring, and spring certainly provides a complete set of mechanisms for dependency injection. The previous article introduces dependency injection in concept. This article focuses on the spring dependency injection method. xml is used here.
Basic Injection
Constructor injection and set-value injection are two main methods of dependency injection. spring has a complete implementation of this method. Below we will briefly describe them in the form of code.
Constructor Injection
Spring containers inject constructor by calling the bean Constructor (which may contain several parameters and each parameter represents a dependency. The static factory method is similar to the calling constructor.
The constructor dependency injection in Spring adopts the following form. Each parameter is configured with the bean label sub-tag <constructor-arg>:
Index: The parameter position in the constructor, starting from 0. The configuration in the tag contains five items, and some of them are used for the configuration of a certain dependency. A simple description is as follows:
Value: The parameter Value. It is usually used with the basic type and type or index.
Name: Name of the parameter in the constructor
Ref: reference other Spring-Managed Objects
Type: the Type of the parameter. The value is a basic Type or a fully qualified class name.
Basic Bean
The following code is annotated to describe the above configuration items. For the referenced class libraries, see previous articles. The first is a simple code structure:
Fruit
Apple and Banana are used to demonstrate ref configuration items. They are just a simple class with no fields. Fruit contains an Apple and a Banana. The Code is as follows:
Package com. test. wdi;/*** @ date 2015-2-27 * @ Description: This class is mainly used to describe the ref items injected by the constructor, including the basic constructor and static factory methods, and instance factory Method */public class Fruit {private Apple; private Banana banana; public Fruit () {super ();} /*** static factory Method */public static Fruit newInstance (Apple apple, Banana banana) {return new Fruit (apple, banana );} /*** instance factory Method */public Fruit newInstance1 (Apple apple, Banana banana) {return new Fruit (apple, banana );} /*** traditional constructors with parameters */public Fruit (Apple apple, Banana banana) {super (); this. apple = apple; this. banana = banana;} public Apple getApple () {return apple;} public void setApple (Apple apple) {this. apple = apple;} public Banana getBanana () {return banana;} public void setBanana (Banana banana) {this. banana = banana ;}@ Override public String toString () {return hashCode () + "Fruit [apple =" + apple + ", banana = "+ banana +"] ";}}
ExampleBean
ExampleBean is used to demonstrate other configuration items except ref. It has a basic type field. Its code is as follows:
Package com. test. wdi;/*** @ date 2015-2-28 * @ Description: This class is used to describe the name index type value in the constructor injection configuration item, to facilitate rewriting of the toString Method */public class ExampleBean {private int years; private String ultimateAnswer; private boolean test; public ExampleBean () {super ();} /*** constructor 2 has two parameters like constructor 1. If the type restriction is not added to bean configuration, * The results will be inconsistent with the expected results */public ExampleBean (int years, boolean test) {this. years = years; this. test = test;}/*** constructor 1 */public ExampleBean (int years, String ultimateAnswer) {this. years = years; this. ultimateAnswer = ultimateAnswer;} @ Override public String toString () {return "ExampleBean [years =" + years + ", ultimateAnswer =" + ultimateAnswer + ", test = "+ test +"] ";}}
BeanXMl Configuration
Bean configuration, which will be described in sequence Simple usage of each configuration attribute in the tag and their combination. Bean configuration contains a connection file. allbean. xml is the main configuration file, which introduces t1.xml through the import tag, and t1.xml contains all the configuration information, with detailed notes:
Test procedure
The test program uses the main function to print out the beans defined in t1 in sequence. The Code is as follows:
Package com. test; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext;/*** @ Description: * In this example, the environment is eclipse */public class TestMain {public static void main (String [] args) {/*** ApplicationContext represents the spring container, while ClassPathXmlApplicationContext is an implementation of it. It reads the corresponding * xml Metadata configuration from the class path and initializes the container. Among them, allbean. xml is the corresponding metadata configuration */ApplicationContext context = new ClassPathXmlApplicationContext ("allbean. xml "); // print the Object System in sequence. out. println (context. getBean ("f1"); System. out. println (context. getBean ("f2"); System. out. println (context. getBean ("f3"); System. out. println (context. getBean ("exam1a"); System. out. println (context. getBean ("exam1b"); System. out. println (context. getBean ("exam2"); System. out. println (context. getBean ("exam3"); System. out. println (context. getBean ("exam4 "));}}
The test results are as follows:
Note: The constructor must pay attention to the circular dependency issue.
Set Value Injection
Set Value injection: after the spring container calls the no-argument constructor or no-argument factory method, it then calls its setter method to inject dependencies.
Set injection is relatively simple. The first example of spring container and configuration in the previous article is setter injection. Below is an xml configuration description:
Dependency injection instance
There are multiple types of dependencies, including basic types (int, double, string, etc.) and complex types (system class and custom class ), the following describes the problems they need to pay attention to during the injection process in sequence.
Set the corresponding labels for the injection and constructor injection And The meanings of their sub-tags are consistent. The following example generally only describes one of them. In addition The unique type and other index values are also consistent.
Direct Type (original type, String, etc)
Directly use the value sub-tag or attribute configuration for the direct type. Spring conversion service automatically converts a string to a real attribute (attribute or constructor parameter ).
Corresponding settings are injected. the javabean specification and name attributes can accurately determine the type, so there is no problem with conversion. However, for Constructor injection, if the type or name is not restricted, unexpected results may be generated.
The following section of configuration is actually a part of the constructor in the above text, and the configuration injection is added for comparison. You can test the running result by yourself:
For java. util. properties, you can use a configuration similar to the following:
jdbc.driver.className=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mydb
Idref tag
The Idref sub-tag only transmits the id of a bean as a dependency to another bean to prevent errors. By passing only the bean id, you can build more flexible programs.
The basic configuration is as follows:
Reference other beans
Referencing other beans is a common scenario in spring. Or Sub-tag Implementation, or through the ref attribute (essentially a abbreviation of a sub-tag ). The sub-TAG provides more specific usage and configuration.
The basic style is as follows:
Or
The difference between the two is that the former searches for objects whose id (name) is someBean in the current spring container and parent container, while the latter only searches for objects in the parent container.
The ref attribute is short for the former.
The following is an example:
Internal bean
In Or Internally defined beans are called internal beans. spring automatically ignores the id, name, and scope attributes. The configuration is as follows:
Set
One of the advantages of Java is that jdk provides a powerful Collection framework, and spring certainly provides a collection injection method.
Since Java, it supports generics. We try to use generics for our collections. In addition, we will not discuss the inheritance of bean definitions involved in collection merging.
First, we introduce a bean with set attributes, omitting the constructor and get set methods.
public class FruitCollection { private Set
fruits; private List
fruitList; private Map
fruitMap; private Properties ppp;}
For details, see the following configuration code:
T1
T2
T3
T4
Null and empty string
Spring supports null injection and empty strings. See the following Configuration:
Actually, the following methods are executed:
setUltimateAnswer(null);setUltimateAnswer("");
Abbreviations
In addition to the standard format used for multiple times, the bean configuration file of Spring also has some simple scaling forms. These scaling forms are based on the xml namespace, they are p-nameplace and c-nameplace, which correspond to seter injection and constructor injection.
I will not go into details here. Directly paste an example in the official spring document to describe the p namespace:
Compound attribute name
Nested injection. fruit has an apple attribute. Assume that apple has a color attribute. Therefore, you can directly inject attributes into the definition of fruit, provided that apple is not null:
End
This article starts from the two dependency injection methods of spring, and then provides specific configuration examples to illustrate the injection instances of major departments in turn. Most of the examples in this article have passed the test and the environment is spring4.1.5. However, I have a limited level and certainly have a lot of improper and incomplete support. I hope to make progress together. The Code address used in this article is: resources in this article (no points)