Spring Framework有两大基石:IOC容器和AOP,本篇通过一个简单的Spring IOC示例 debug来探究一下Spring FrameworkIOC容器内部实现。
示例
import com.bytebeats.spring.research.model.User;
import com.bytebeats.spring.research.service.UserService;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
/**
* Hello world!
*
*/
public class App {
public static void main( String[] args ) {
ClassPathResource resource = new ClassPathResource("spring-bean.xml");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(resource);
User user = new User();
user.setId(15L);
user.setName("ricky");
//测试类
UserService userService = factory.getBean("userService", UserService.class);
boolean success = userService.addUser(user);
System.out.println("success:"+success);
}
}
spring-bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="userDao" class="com.bytebeats.spring.research.dao.UserDao" />
<bean id="userService" class="com.bytebeats.spring.research.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao" />
</bean>
</beans>
UserDao
public class UserDao {
public int insert(User user){
return 1;
}
}
UserService
public interface UserService {
boolean addUser(User user);
}
UserServiceImpl
public class UserServiceImpl implements UserService {
private UserDao userDao;
@Override
public boolean addUser(User user) {
int update = userDao.insert(user);
return update>0;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}