applicationContext.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"> <!-- 属性注入 --> <bean id="userHello" class="com.shuoeasy.test.User"> <property name="name" value="老鹰开灰机"></property> </bean> <!-- 构造注入 --> <bean id="seller" class="com.shuoeasy.test.Seller"> <constructor-arg type="String" value="我是商家"></constructor-arg> <constructor-arg type="double" value="5000"></constructor-arg> <constructor-arg type="boolean" value="false"></constructor-arg> </bean> <bean id="seller2" class="com.shuoeasy.test.Seller"> <constructor-arg type="String" > <value><![CDATA[我是含有非法字符串的<数据]]></value> </constructor-arg> <constructor-arg type="double" value="5000"></constructor-arg> </bean> </beans>
User.class:
package com.shuoeasy.test;
public class User {
private String name;
public void setName(String name){
this.name = name;
}
public void hello(){
System.out.println("你好:" + this.name);
}
}Seller.class:
package com.shuoeasy.test;
public class Seller {
private String name;
private double money;
private boolean sex;
public Seller(String name, double money){
this.name = name;
this.money = money;
}
public Seller(String name, double money, boolean sex) {
super();
this.name = name;
this.money = money;
this.sex = sex;
}
@Override
public String toString() {
return "Seller [name=" + name + ", money=" + money + ", sex=" + sex + "]";
}
}Main.class
package com.shuoeasy.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
/*属性注入*/
// 1.创建Spring的IOC容器对象
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// 2.从IOC容器中获取Bean实例
// 利用id定位到IOC容器
User user = (User) ctx.getBean("userHello");
// User user = ctx.getBean(User.class); // 不建议使用
// 3.调用
user.hello();
/*构造注入*/
Seller seller = (Seller) ctx.getBean("seller");
System.out.println(seller);
Seller seller2 = (Seller) ctx.getBean("seller2");
System.out.println(seller2);
}
}输出:
你好:老鹰开灰机
Seller [name=我是商家, money=5000.0, sex=false]
Seller [name=我是含有非法字符串的<数据, money=5000.0, sex=false]