Part I: Spring's IoC (Inversion of Control) 2
In the previous article beans.xml
, we specified the class object that needs to be instantiated. In Spring
the IoC
default construction method called to create an object is no-parameter construction.
Here is a good test:
modify the following UserServiceImpl
categories, as follows:
public class UserServiceImpl implements UserService{
private UserDao userDao;
// set注入
public void setUserDao(UserDao dao){
this.userDao = dao;
}
public UserServiceImpl(){
System.out.println("UserServiceImpl无参数构造!");
}
public UserServiceImpl(UserDao dao){
this.userDao = dao;
System.out.println("UserServiceImpl有参构造!");
}
public void getUserService() {
userDao.getUser();
}
}
Test at this time:
public class myTest {
@Test
public void Test(){
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = (UserService) context.getBean("userService");
userService.getUserService();
}
}
Still call Test
, and then there is no problem, the test results are as follows: It
can be seen that the default constructor is no-argument constructor.
Then we beans.xml
pass in the change object in:
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mySqlDao" class="com.dao.UserMySQLImpl"/>
<bean id="oracleDao" class="com.dao.UserOracleImpl"/>
<bean id="userService" class="com.service.UserServiceImpl">
<constructor-arg type="com.dao.UserDao" ref="oracleDao"/>
</bean>
</beans>
Specify the incoming type, and reference.
Then execute Test
: the
constructor parameter passes the document address: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-constructor-injection
Reference video address: https://www.bilibili.com/video/BV1WE411d7Dv?p=6