In spring, IOC control inversion is a key part of spring. Next we will briefly describe the springIOC application through a simple case, note the following injection methods: ID and name, and basic attribute injection:
1. Create a Java project and add the Jar package:
In this step, we first need to create a java project and then import the relevant Jar package support. Here I will explain the Jar package to be imported:
They are:
A. Spring. jar contains information about control inversion.
B. Commons-logging.jar is used to output logs.
2. Write a program to obtain the java object in the BeanFactory container.
A. Write the Java class for IOC
// The class is very simple. Only one method can be used for testing.
Public void addUser (){
System. out. println ("============== ");
}
B. Compile the beans. xml file.
<? 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>
<Bean id = "userAction" class = "com. spring. action. UserAction"/>
</Beans>
C. Compile the test class JunitTestCase.
@ Test
Public void test01 (){
// Obtain the container object
BeanFactory applicationContext = new ClassPathXmlApplicationContext ("beans. xml ");
// Obtain the configured bean
UserAction user = (UserAction) applicationContext. getBean ("userAction ");
Call related methods
User. addUser ();
}
Output result:
================
Setter injection: Same principle as above. It's just that we don't have the attributes in the new class. Instead, it only declares it. Then, assign the values in the container through reflection:
In the following class, the userService attribute is not new. But it has a set method. The value assignment method is specified in the configuration file:
Java files
Public class UserAction {
Private UserService userService;
Public void setUserService (UserService userService ){
This. userService = userService;
}
Public void addUser (){
UserService. HelloWorld ();
}
}
Xml configuration file:
<Bean id = "userService" class = "com. spring. service. UserServiceImpl">
<Property name = "userDao" ref = "userDao"> </property>
</Bean>
<! -The biggest difference between the following IDs and names is that names can have special characters, but they cannot have -->
<Bean id = "userAction" class = "com. spring. action. UserAction">
<Property name = "userService" ref = "userService">
<! -Basic attribute Injection Method -->
<Value> helloworld </value>
</Property>
</Bean>
Here we first specify the bean of userService. Then, the bean is specified to the Action property value according to the property. That is, the value is assigned to the past.
There are also three injection methods. Setter, constructor, and Interface.
We often use Setter. Here we will only introduce the setter method.
Author: zhang6622056