Java BeanFactory
快速入门
Ioc思想实现
- 1.创建普通的Maven项目
- 2.在pom.xml文件中的project标签内导入Spring的jar包
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
......
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.7</version>
</dependency>
</dependencies>
</project>
- 3.创建UserService接口
- 4.创建UserServiceImpl类,并且继承UserService接口
- 5.在resources中创建beans.xml文件,并且配置bean
<?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.xsd">
<bean id="userService" class="org.example.UserServiceImpl"></bean>
</beans>
public static void main(String[] args) {
// 创建工厂对象
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
// 创建一个读取器(xml文件)
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
// 读取配置文件给工厂
reader.loadBeanDefinitions("beans.xml");
// 根据id获取bean实例对象
UserService userService = (UserService) beanFactory.getBean("userService");
System.out.println(userService);
}
DI思想实现,依赖注入
- 1.创建UserDao接口和UserDaoIpml类,类继承UserDao接口
- 2.在UserServiceImpl类中新建一个set方法,用于接受设置注入的对象
public class UserServiceImpl implements UserService{
// BeanFactory去调用该方法 从容器中获得userDao设置到此处
public void setUserDao(UserDao userDao){
System.out.println("BeanFactory去调用该方法 从容器中获得userDao设置到此处" + userDao);
}
}
- 3.配置beans.xml文件,在bean标签中添加property标签实现依赖注入
<?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.xsd">
<bean id="userService" class="org.example.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="org.example.UserDaoImpl"></bean>
</beans>
// 创建工厂对象
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
// 创建一个读取器(xml文件)
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
// 读取配置文件给工厂
reader.loadBeanDefinitions("beans.xml");
// 根据id获取bean实例对象
UserService userService = (UserService) beanFactory.getBean("userService");
System.out.println(userService);
BeanFactory去调用该方法 从容器中获得userDao设置到此处org.example.UserDaoImpl@49c43f4e
org.example.UserServiceImpl@290dbf45
评论 (0)