直接给类成员变量赋值测试:
- 导入Spring所需依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
- 建立实体类,编写get、set方法
public class Hello {
private String str;
public void setStr(String str){
this.str=str;
}
public String getStr(){
return str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
- 编写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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.Nana.pojo.Hello">
<property name="str" value="hello"></property>
</bean>
</beans>
- 测试
public class MyTest {
public static void main(String[] args) {
ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("beans.xml");
Hello hello = (Hello)classPathXmlApplicationContext.getBean("hello");
System.out.println(hello);
}
}
先注册再引用核心代码:
<bean id="mysqlImpl" class="com.Nana.dao.UserDaoMysql"></bean>
<bean id="oracleImpl" class="com.Nana.dao.UserDaoOracle"></bean>
<bean id="UserServiceImpl" class="com.Nana.service.UserServiceImpl">
<property name="userDao" ref="mysqlImpl"></property>
</bean>
- ref:引用Spring容器中创建好的对象
- value:适用于基本数据类型,给成员变量赋值
ClassPathXmlApplicationContext和ApplicationContext的继承关系: