这里主要是使用org.springframework:spring-beans:5.2.0.RELEASE进行分析
- Bean是Spring中最重要的部分之一,我们定义一个POJO让它成为Bean
package com.xizi.pojo;
public class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Hello{" +
"name='" + name + '\'' +
'}';
}
}
- 接下来将类注入配置文件中 将POJO成为Bean注入Spring容器
<?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就是java对象 , 由Spring创建和管理-->
<bean id="hello" class="com.xizi.pojo.Hello">
<property name="name" value="Spring"/>
</bean>
</beans>
1. ApplicationContext容器
- 测试代码展示
import com.xizi.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
// 获取上下文2对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//对象都在Spring中管理 要使用直接取出来
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello);
}
}
这里使用ApplicationContext容器
2. BeanFactory 容器
使用BeanFactory作为容器测试
import com.xizi.pojo.Hello;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
public class MyTest {
public static void main(String[] args) {
BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
Hello hello = (Hello) beanFactory.getBean("hello");
System.out.println(hello);
}
}
结果一致