spring入门
什么是spring?
Spring是为企业应用的开发提供轻量级解决方法。包括:基于依赖注入的核心机制、基于AOP的声明式事务管理、与多种持久层技术的整合,以及优秀的Web MVC框架等。Spring贯穿表现层、业务层、持久层。
Spring优点:
- 低侵入式设计代码污染低。
- 独立于各种应用服务器。
- Spring的IOC容器降低了业务对象替换的复杂性,提高组件之间的解耦。(高内聚,低耦合)
- Spring的AOP支持允许将一些通用任务如安全、事物、日志等进行集中式处理,从而提供更好的复用。
- Spring的ORM和DAO提供了与第三方持久层框架的良好整合,简化了底层的数据库访问。
Spring的高度开放性,并不强调应用完全依赖与Spring,开发者可自由选择所需部分。
Spring框架的组成结构图 :
用Eclipse创建一个Spring项目:
1.创建web文件 File——new——web project
2.在项目目录WebRoot下的WEB-INF下的文件夹lib添加以下jar包
3.全选jar包右键选择Build Path下的Add to build Path
如图:
4.修改applicationContext.xml配置文件
默认xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd”
修改成xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd”
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
</beans>
Spring管理Bean
1.创建实体类
package com.bdqn.entity;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println(this.getName());
}
}
2.在applicationContext.xml配置文件添加bean
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<bean id="PersonName" class="com.bdqn.entity.Person">
<property name="name">
<value>qwertyuiopasdfghjklzxcvbnm</value>
</property>
</bean>
</beans>
3.测试类
package com.bdqn.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bdqn.entity.Person;
public class Text {
public static void main(String[] args) {
//加载applicationContext.xml文件
ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
//获得文件中的Bean属性
Person person=(Person) context.getBean("PersonName");
person.show();
}
}