spring框架核心jar包:
在工作目录下建立spring配置文件:
- setter注入
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
//定义一个bean,它名字叫P1,class后为实现类,属性name设置为micro,为非单例模式
<bean id="P1" class="micro.Person" destroy-method="close" scope = "prototype">
<property name="name" value = "micro" />
</bean>
</beans>
创建实体类Person:
package micro;
/**
@author:micro_hz
2015年8月11日
*/
public class Person {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试代码:
package micro;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
@author:micro_hz
2015年8月11日
*/
public class Test {
public static void main(String args[])
{
//加载配置文件
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("Spring.xml");
//工厂模式得到该实例
Person p = (Person) context.getBean("P1");
System.out.println(p.getName());
}
}
运行结果:
micro
- 构造注入:
spring.xml文件修改为:
<bean id="P1" class="micro.Person" destroy-method="close" scope = "prototype">
<constructor-arg value = "master"></constructor-arg>
</bean>
实体类Person添加构造方法:
public class Person {
String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试:
public class Test {
public static void main(String args[])
{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("Spring.xml");
Person p = (Person) context.getBean("P1");
System.out.println(p.getName());
}
}
输出:
master