A simple reference for using Spring-IoC:
Analysis of simple instances of spring ioc and scope attributes of beans
1. Inject different data types through the set method
Test class code (the properties injected in set method must be added with the set method)
/**Injection example through set method*/public class IoC_By_Set {/**Inject Integer type parameter*/private Integer id;/**Inject String type parameter*/private String name;/**Inject entity Bean*/private User user;/**Inject array*/private Object[] array;/**Inject List collection*/private List<Object> list;/**Inject Set collection*/private Set<Object> set;/**Inject Map key-value pairs*/private Map<Object, Object> map;/**Inject properties type*/private Properties properties;/**Inject empty string*/private String emptyValue;/**Inject null value*/private String nullValue = "";/**Detection whether all the injected properties are correct*/public Boolean checkAttr() {if(id == null) {return false;} else {System.out.println("id:" + id);}System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- name);}System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- array) {System.out.println(object.toString());}}System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ {System.out.println("set:");for (Object object : set) {System.out.println(object.toString());}}System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ {System.out.println(entry.getKey() + "|" + entry.getValue());}}System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- entry.getValue());}}System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- setName(String name) {this.name = name;}public void setUser(User user) {this.user = user;}public void setArray(Object[] array) {this.array = array;}public void setList(List<Object> list) {this.list = list;}public void setSet(Set<Object> set) {this.set = set;}public void setMap(Map<Object, Object> map) {this.map = map;}public void setProperties(Properties properties) {this.properties = properties;}public void setEmptyValue(String emptyValue) {this.emptyValue = emptyValue;}public void setNullValue(String nullValue) {this.nullValue = nullValue;}}applicationContext.xml configuration
<!-- set injection--> <bean id="ioC_By_Set"> <!-- Injection id attribute--> <property name="id" value="1"/> <!-- Using <!-- Handling XML special characters with <!-- Using <![CDATA[]]> tags---> <property name="name"> <!-- You can also use P&G --> <value><![CDATA[P&G]]></value> </property> <!-- Defining internal bean injection--> <property name="user"> <bean> <property name="id" value="1"/> <property name="userName" value="internal bean"/> <property name="passWord" value="233"/> </bean> </property> <!-- Inject array type--> <property name="array"> <array> <!-- Define array elements--> <value>array01</value> <value>array02</value> <value>array03</value> </array> </property> <!-- Inject List type--> <property name="list"> <list> <!-- Define elements in list--> <value>list01</value> <value>list02</value> <value>list03</value> </list> </property> <!-- Inject Set type--> <property> <property--- Define elements in list--> <value>list02</value> <value>list03</value> </list> </property> <!-- Inject Set type--> <property name="set"> <set> <!-- Define elements in set --> <value>set01</value> <value>set02</value> <value>set03</value> </set> </property> <!-- Inject Map type--> <property name="map"> <map> <!-- Define key-value pairs in map --> <entry> <key> <value>mapKey01</value> </key> <value>mapValue01</value> </entry> <entry> <key> <value>mapKey02</value> </key> <value>mapValue02</value> </entry> </map> </property> <!-- Inject properties types --> <property name="properties"> <props> <!-- Define key-value pairs in properties --> <prop key="propKey1">propValue1</prop> <prop key="propKey2">propValue2</prop> </props> </property> <!-- Inject empty string --> <property name="emptyValue"> <value></value> </property> <!-- Inject null value --> <property name="nullValue"> <null/> </property> </bean>
Test code
public class IoC_Test {private ApplicationContext ctx;@Before public void load() {//Read applicationContext.xml configuration file ctx = new ClassPathXmlApplicationContext("applicationContext.xml");}@Test public void SetTest() {IoC_By_Set ioc = (IoC_By_Set) ctx.getBean("ioC_By_Set");ioc.checkAttr();}}Console results:
id:1--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 3----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ! !
2. Inject various types of attributes through construction methods
Note: When using JDK1.8 version, please upgrade the spring-related jar package to version 4.x or above, otherwise incompatible constructors will be injected.
Test class code
/** Example of injection through constructor*/public class IoC_By_Constructor {private Integer id;private String name;private User user;private List<Object> list;public IoC_By_Constructor() {}public IoC_By_Constructor(Integer id, String name, User user, List<Object> list) {this.id = id;this.name = name;this.user = user;this.list = list;}/** Check whether the injection is successful*/public Boolean checkAttr() {if(id == null) {return false;} else {System.out.println("id:" + id);}System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + "|" + user.getUserName() + "|" + user.getPassWord());}System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ true;}}applicationContext.xml configuration
<!-- Constructor-arg value="P&G"/> <!-- Injection object--> <bean id="ioC_By_Constructor"> <!-- Injection object--> <bean> <constructor-arg value="1" type="java.lang.Integer"/> <!-- Injection string--> <constructor-arg value="P&G"/> <!-- Injection object--> <constructor-arg> <!-- Built-in object--> <bean> <constructor-arg value="1"/> <constructor-arg value="Construction internal bean"/> <constructor-arg value="666"/> </bean> </constructor-arg> <!-- Inject collection--> <constructor-arg> <list> <value>list01</value> <value>list02</value> <value>list03</value> </list> </constructor-arg> </bean>
Test code:
public class IoC_Test {private ApplicationContext ctx;@Before public void load() {//Read applicationContext.xml configuration file ctx = new ClassPathXmlApplicationContext("applicationContext.xml");}@Test public void constructorTest() {IoC_By_Constructor ioc = (IoC_By_Constructor) ctx.getBean("ioC_By_Constructor");ioc.checkAttr();}}Console results:
id:1--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ! !
3. Automatic injection (automatic assembly)
Although automatic assembly can save some code, it is not recommended to use it
Test class code:
/**Auto assembly injection*/public class IoC_By_Auto {private User user;/**Check whether the injection is successful*/public Boolean checkAttr() {if(user == null) {return false;} else {System.out.println("user:" + user.getId() + "|" + user.getUserName() + "|" + user.getPassWord());}System.out.println("Correct!!!");return true;}/**The automatic assembly attribute requires setting the set method*/public void setUser(User user) {this.user = user;}}applicationContext.xml configuration
<!-- Beans obtained by automatic assembly --> <bean id="user"> <property name="id" value="1"/> <property name="userName" value="auto-assembly"/> <property name="passWord" value="233"/> </bean> <!-- Bean autowire:byName Autowire:byName According to the property name of the class, find the only bean of matching type according to the property type of the class. If multiple beans match, throw an exception constructor matches the corresponding bean according to the constructor parameter type of the class. No. Default, means that automatic assembly default is not used: determined by the default-autowire property of the upper label <beans>--> <bean id="ioC_By_Auto" autowire="byName"></bean>
Test code
public class IoC_Test {private ApplicationContext ctx;@Before public void load() {//Read applicationContext.xml configuration file ctx = new ClassPathXmlApplicationContext("applicationContext.xml");}@Test public void AutoTest() {IoC_By_Auto ioc = (IoC_By_Auto) ctx.getBean("ioC_By_Auto");ioc.checkAttr();}}Console results
user:1|Automatic assembly|233 is correct! ! !
The above is using the byName mode. The configuration code of other modes has been indicated and no testing is performed.
4. Inject attributes using P namespace
Test class code
/**Injection using P namespace*/public class IoC_By_P {private Integer id;private String name;private User user;/**Check whether the injection is successful*/public Boolean checkAttr() {if(id == null) {return false;} else {System.out.println("id:" + id);}System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- name);}System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- id) {this.id = id;}public void setName(String name) {this.name = name;}public void setUser(User user) {this.user = user;}}applicationContext.xml configuration
<!-- Inject various types of properties using the P namespace--> <bean id="user2"> <property name="id" value="1"/> <property name="userName" value="P"/> <property name="passWord" value="233"/> </bean> <bean id="ioC_By_P" p:id="1" p:name="namespace" p:user-ref="user2"></bean>
Test code
public class IoC_Test {private ApplicationContext ctx;@Before public void load() {//Read applicationContext.xml configuration file ctx = new ClassPathXmlApplicationContext("applicationContext.xml");}@Test public void PTest() {IoC_By_P ioc = (IoC_By_P) ctx.getBean("ioC_By_P");ioc.checkAttr();}}Console results
id:1--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ! !
5. Inject using annotation method
Spring has provided Annotation-based injection after 3.0.
1.@Autowired-Annotation of member variables, methods and constructors to complete the automatic assembly work. It is not recommended to use it.
2.@Qualifier-Combined with @Autowired to solve the assembly of multiple beans of the same type
3. @Resource-JSR-250 standard annotation, the function is equivalent to @Autowired, but @Autowired is automatically injected according to byType, while @Resource is automatically injected according to byName by default.
4.@PostConstruct - Add annotation @PostConstruct to the method, and this method will be executed by the Spring container after bean is initialized.
5.@PreDestroy-Add annotation @PreDestroy on the method, this method will be executed by the Spring container after bean is initialized.
6.@Component-Only add a @Component annotation to the corresponding class, the class is defined as a bean. It is not recommended to use it. It is recommended to use three more refined types: @Repository, @Service, @Controller
@Repository Storage Layer Bean
@Service Business Layer Bean
@Controller Display Layer Bean
7.@Scope-Define the scope of the bean
First configure applicationContext.xml to enable annotation
<!-- Scan the annotated class in the package--> <context:component-scan base-package="com.bc.ioc.demo05"/>
Entity Bean annotation
@Repositorypublic class User {private Integer id = 1;private String userName = "Annotation injection";private String password = "233";public User() {super();}public User(Integer id, String userName, String password) {super();this.id = id;this.userName = userName;this.passWord = password;}public Integer getId() {return id;}public String getUserName() {return userName;}public String getPassWord() {return password;}public void setId(Integer id) {this.id = id;}public void setUserName(String userName) {this.userName = userName;}public void setPassWord(String password) {this.passWord = password;}}Test class code annotation
/**Inject attributes using annotations*/@Service("ioC_By_Annotation")public class IoC_By_Annotation {@Resource private User user;public void setUser(User user) {this.user = user;}/**Check whether the injection is successful*/public Boolean checkAttr() {if(user == null) {return false;} else {System.out.println("user:" + user.getId() + "|" + user.getUserName() + "|" + user.getPassWord());}System.out.println("Correct!!!");return true;}}Test code
public class IoC_Test {private ApplicationContext ctx;@Before public void load() {//Read applicationContext.xml configuration file ctx = new ClassPathXmlApplicationContext("applicationContext.xml");}@Test public void annotationTest() {IoC_By_Annotation ioc = (IoC_By_Annotation) ctx.getBean("ioC_By_Annotation");ioc.checkAttr();}}Console output
After testing, using annotation injection. If the applicationContext.xml is configured with other injection methods, an error will be reported, which will also cause other injection methods to be abnormal.
user:1|Annotation injection|233 is correct! ! !
6. Bean injection by configuring the static factory method
Static factory code
/**Static Factory*/public class StaticFactory {public static Integer getId() {return 1;}public static String getName() {return "static factory";}public static User getUser() {return new User(1, "Factory User", "666");}}Test class code
/** Injection through static factory*/public class IoC_By_StaticFactory {private Integer id;private String name;private User user;/** Check whether the injection is successful*/public Boolean checkAttr() {if (id == null) {return false;} else {System.out.println("id:" + id);}System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- name);}System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- id) {this.id = id;}public void setName(String name) {this.name = name;}public void setUser(User user) {this.user = user;}}applicationContext.xml configuration
<!-- Configuring the static factory method Bean is actually configuring the value returned by the factory method as a bean --> <bean id="factory_id" factory-method="getId"/> <bean id="factory_name" factory-method="getName"/> <bean id="factory_user" factory-method="getUser"/> <bean id="ioC_By_StaticFactory"> <property name="id" ref="factory_id"/> <property name="name" ref="factory_name"/> <property name="user" ref="factory_user"/> </bean>
Test code
public class IoC_Test {private ApplicationContext ctx;@Before public void load() {//Read applicationContext.xml configuration file ctx = new ClassPathXmlApplicationContext("applicationContext.xml");}@Test public void staticFactoryTest() {IoC_By_StaticFactory ioc = (IoC_By_StaticFactory) ctx.getBean("ioC_By_StaticFactory");ioc.checkAttr();}}Console output results
id:1--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ! !
7. Injection through the example factory method
The difference from a static factory is that the instance factory is not static. You need to first new instance factory object before you can configure its method. The new object is also managed by spring.
Factory Code
/**Instance Factory*/public class Factory {public Integer getId() {return 1;}public String getName() {return "Instance Factory";}public User getUser() {return new User(1, "Instance Factory User", "233");}}Test class code
/**Instance factory injection*/public class IoC_By_Factory {private Integer id;private String name;private User user;/** Check whether the injection is successful*/public Boolean checkAttr() {if (id == null) {return false;} else {System.out.println("id:" + id);}System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- name);}System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- id) {this.id = id;}public void setName(String name) {this.name = name;}public void setUser(User user) {this.user = user;}}applicationContext.xml configuration
<!-- Configure the instance factory bean --> <bean id="factory"/> <!-- Configure the instance factory method Bean --> <bean id="f_id" factory-bean="factory" factory-method="getId"/> <bean id="f_name" factory-bean="factory" factory-method="getName"/> <bean id="f_user" factory-bean="factory" factory-method="getUser"/> <!-- Inject the corresponding instance factory method Bean --> <bean id="ioC_By_Factory"> <property name="id" ref="f_id"/> <property name="name" ref="f_name"/> <property name="user" ref="f_user"/> </bean>
Test class code
public class IoC_Test {private ApplicationContext ctx;@Before public void load() {//Read applicationContext.xml configuration file ctx = new ClassPathXmlApplicationContext("applicationContext.xml");}@Test public void factoryTest() {IoC_By_Factory ioc = (IoC_By_Factory) ctx.getBean("ioC_By_Factory");ioc.checkAttr();}}Console output
id:1--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ! !
Summarize
The above is all about this article's brief discussion on the injection method of spring ioc and the injection of different data types. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!