3、使用Sping来接管创建对象
3.1 第一步 新建一个实体类
package pojo;
public class Hello {
private String str ;
public Hello(){
}
public Hello(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
3.2 第二步 编写beans.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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用Sping来创建对象 在Sping中都成为Bean-->
<bean id="hello" class="pojo.Hello">
<!--Hello hello = new Hello() 其中id类似于变量指向对象地址 class类似于创建对象的模板 类 bean类似于创建的对象 property属性-->
<property name="str" value="Hello Sping"/>
</bean>
</beans>
3.3 第三步 测试
package pojo;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Mytest {
@Test
public void test(){
/*获取容器*/
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
/*从容器里面取出对象 context.getBean("hello", Hello.class)其中hello.class限定了返回值类型 */
Hello hello = context.getBean("hello", Hello.class);
System.out.println(hello);
}
}
标签:context,String,Sping,接管,创建对象,public,class,str,Hello
From: https://www.cnblogs.com/advancingSnail/p/18158801