Spring Dependencies Injection1, Construtor argsinjection1.1 Ref injection
<beans> <bean id= "foo" class= "X.y.foo" > <constructor-arg ref= "bar"/> <constructor-ar G ref= "Baz"/> </bean> <bean id= "bar" class= "X.y.bar"/> <bean id= "baz" class= "X.y.baz"/></ Beans>package X.y;public class Foo {public Foo (bar bar, Baz Baz) {//...}}
An injection is performed based on the type matching the corresponding constructor parameter.
1.2 Specifying type Injection
public class Examplebean {//number of years to calculate the Ultimate Answer private int years; The Answer to life, the Universe, and everything private String ultimateanswer; Public Examplebean (int years, String ultimateanswer) {this.years = years; This.ultimateanswer = Ultimateanswer; }}<bean id= "Examplebean" class= "examples. Examplebean "> <constructor-arg type=" int "value=" 7500000 "/> <constructor-arg type=" Java.lang.String "Val Ue= "/></bean>"
1.3 Specify Index Injection
<bean id= "Examplebean" class= "examples. Examplebean "> <constructor-arg index=" 0 "value=" 7500000 "/> <constructor-arg index=" 1 "value="/>< " ;/bean>
1.4 Using Annotation Injection
Package Examples;public class Examplebean {//Fields omitted @ConstructorProperties ({"Years", "Ultimateanswer"}) Public Examplebean (int years, String ultimateanswer) {this.years = years; This.ultimateanswer = Ultimateanswer; }}
2, setter-based Dependency Injection
It is time to use the constructor to inject, when to use the setter, an experience said: the necessary parameters need to be injected into the constructor, the other can be used setter, but also can be used @required annotation to display the specified parameters
2.1 Simple Set-injection
Public class simplemovielister { // the simplemovielister has a dependency on the MovieFinder private moviefinder moviefinder; // a setter method so that The spring container can inject a moviefinder public void setmoviefinder (Moviefinder moviefinder) { this.movieFinder = movieFinder; } // business logic that actually uses the injected moviefinder is Omitted ...} <bean id= "Simplemovielister" class = "..." > <property name = "Moviefinder" ref = "Moviefinder" ></property></bean>
2.2
Spring Dependencies Injection