简单的介绍一下Spring吧,Spring翻译过来是春天的意思,它是一个致力于提供一种方法管理你的业务对象的轻量级的开源框架。
我们为什么要用Spring框架呢?他有什么好处?配置文件那么麻烦,还容易配错。
我的观点是可以降低耦合,Spring的底层使用了单例模式保证了一个对象在应用程序中只会存在一个实例,还便于后期的维护
怎么用Spring?
去Spring官网下载Spring的插件安装到eclipse,maven工程在pom.xml文件里面添加Spring依赖
<!-- 添加spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
新建人的实体类
public class Person {
private int pid;
private int pname;
public Person() {
}
public Person(int pid, int pname) {
this.pid = pid;
this.pname = pname;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public int getPname() {
return pname;
}
public void setPname(int pname) {
this.pname = pname;
}
}
新建Spring Bean Configuration File配置文件然后在配置文件里面配置
<?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="person" class="com.mu.entity.Person">
<property name="pid" value="1"></property>
<property name="pname" value="测试"></property>
</bean>
</beans>
去测试类引用测试
public class TestSpring {
@Test
public void testPerson() {
//读取Spring配置文件
BeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
//通过配置文件取得实体类
Person person=(Person) beanFactory.getBean("person");
System.out.println(person);
}
}
未完待续.........