1.Spring:提供了许多轻量级应用开发实践的工具集合,这些工具集以接口,抽象类,或工具类的形式存在于Spring中
通过使用这些工具集,可以实现应用程序与各种开源技术及框架间的友好整合。
2.Spring的使用:
1.离线下载Spring 的插件 2.在线下载插件
本文使用的是:在线下载
还需导入依赖:
<!-- 引入Spring依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
这样就可以运用Spring了。
例如:
有person类:
package com.zking.entity;
import java.util.List;
public class Person {
private int pid;
private String pname;
private List<String> phobbies;
public List<String> getPhobbies() {
return phobbies;
}
public void setPhobbies(List<String> phobbies) {
this.phobbies = phobbies;
}
public Person() {
super();
}
public Person(int pid, String pname) {
super();
this.pid = pid;
this.pname = pname;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
@Override
public String toString() {
return "Person [pid=" + pid + ", pname=" + pname + "]";
}
}
运用Spring 则需要配置xml,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="person" class="com.zking.entity.Person">
<!-- 设值:注入
1.set注入
2.构造注入 -->
<property name="pid" value="2"></property>
<property name="pname" value="晶晶"></property>
<property name="phobbies">
<list>
<value>阅读</value>
<value>唱歌</value>
<value>写作</value>
</list>
</property>
<!--引用实体类-->
<!--<property name="card" ref="card"></property>-->
<!-- <constructor-arg value="3"></constructor-arg>
<constructor-arg value="铛铛"></constructor-arg> -->
</bean>
<!--<bean name="card" class="com.zking.entity.Card">
<property name="cid" value="1"></property>
<property name="cnum" value="432501"></property>
</bean>-->
</beans>
要测试了
package com.zking.test;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import com.zking.entity.Person;
public class PersonTest {
@Test
public void test() {
//懒加载 迟缓加载
// BeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("application.xml"));
// Person person=(Person) beanFactory.getBean("person");
// /*person.setPid(1);
// person.setPname("dd");*/
// System.out.println(person.toString());
// System.out.println(person.getPhobbies());
//及时加载
ApplicationContext ac=new ClassPathXmlApplicationContext("application.xml");
Person person2=(Person) ac.getBean("person");
System.out.println(person2.getPname());
System.out.println(person2.getCard().getCnum());
}
}