聊聊程序-Spring IOC之XML实现篇
Posted 小韩聊程序
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了聊聊程序-Spring IOC之XML实现篇相关的知识,希望对你有一定的参考价值。
Person_constructor.java
public class Person_constructor {
String name;
int age;
PC pc;
Person_constructor(){}
public Person_constructor(String name, int age, PC pc){
this.name = name;
this.age = age;
this.pc = pc;
}
public String toString() {
return "Person_constructor{" +
"name='" + name + '\'' +
", age=" + age +
", pc=" + pc +
'}';
}
}
class PC{
String msg = "pc";
}
Person_set.java
public class Person_set {
String name;
int age;
PS ps;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setPs(PS ps) {
this.ps = ps;
}
public String toString() {
return "Person_set{" +
"name='" + name + '\'' +
", age=" + age +
", ps=" + ps +
'}';
}
}
class PS{
String msg = "ps";
}
spring.xml
<!-- XML2IOC - 构造注入和set注入 -->
<bean id="pc" class="cn.shh.test.maven_ssm.module.ioc.xml2ioc.PC"/>
<bean id="person_constructor" class="cn.shh.test.maven_ssm.module.ioc.xml2ioc.Person_constructor"
scope="singleton" >
<constructor-arg index="0" name="name" type="java.lang.String" value="八戒"/>
<constructor-arg index="1" name="age" type="int" value="30"/>
<constructor-arg index="2" name="pc" ref="pc"/>
</bean>
<bean id="ps" class="cn.shh.test.maven_ssm.module.ioc.xml2ioc.PS" />
<bean id="person_set" class="cn.shh.test.maven_ssm.module.ioc.xml2ioc.Person_set"
scope="singleton" >
<property name="name" value="悟空"/>
<property name="age" value="30"/>
<property name="ps" ref="ps"/>
</bean>
App.java
public class App {
public static void main(String[] args) {
// String springXmlLocation = "D:\\maven_ssm\\src\\main\\resources\\spring.xml";
// ApplicationContext fsContext = new FileSystemXmlApplicationContext(springXmlLocation);
ApplicationContext cpContext = new ClassPathXmlApplicationContext("spring.xml");
Person_constructor pc = (Person_constructor) cpContext.getBean("person_constructor");
System.out.println(pc.toString());;
Person_set ps = (Person_set) cpContext.getBean("person_set");
System.out.println(ps.toString());;
}
}
以上是关于聊聊程序-Spring IOC之XML实现篇的主要内容,如果未能解决你的问题,请参考以下文章