spring: 开源,轻量级框架,管理对象容器,主要有 IOC (控制反转),DI(注入属性)
1. 使用Spring框架的好处是什么?
1.降低了组件之间的耦合性 ,实现了软件各层之间的解耦
2.可以使用容易提供的众多服务,如事务管理,消息服务等
3.容器提供单例模式支持
4.容器提供了AOP技术,利用它很容易实现如权限拦截,运行期监控等功能
5.容器提供了众多的辅助类,能加快应用的开发
6.spring对于主流的应用框架提供了集成支持,如hibernate,JPA,Struts等
7.spring属于低侵入式设计,代码的污染极低
8.独立于各种应用服务器
Spring xml配置
1.资源文件配置 classpath
< context:property-placeholder location = "classpath:db.properties" >
2.数据源配置
<bean id = "dataSource" class="org.apache.commons.dbcp2.BasicDataSource"><property name="driverClassName" value="${jdbc.driver}"> // 注意name<property name="url" value="${jdbc.url}"><property name="username" value="${jdbc.username}"><property name= "password" value="${jdbc.password}"></bean>
3.spring-template
<bean id="template" class=""><property name="dataSource" ref="dataScource"></bean>
4.事务管理配置、
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
5.事务通知
< tx:advice id="Active" transaction-manager="txManager">< tx:attriubutes><tx:method name="trans"/></tx:attriubutes></tx:advice>
6切面
<aop:config><aop:pointcut expression="execution(* com.zhiyou.pojo.*Dao.*(..)" id="pointcut"><aop:advisor advice-ref="Actice" pointcut-ref="pointcut"></aop:config>
7.bean管理
<bean id="UserDao" class ="com.zhiyou100.UserDaoImpl"/>
ApplictionContext与Beanfactory 区别:
Beanfactory:读取bean配置文档,管理实例化加载bean,维护bean之间依赖关系
Applicationcontext:继承了Beanfactory ,具有Beanfactory功能,同时提供了以下功能
1.国际化
2.支持AOP
3.统一资源加载
4.消息机制
实例
HelloWorld.java 文件
public class HelloWorld {private String message;public void setMessage(String message){this.message = message;}public void getMessage(){System.out.println("Your Message : " + message);}}
下面是第二个文件 MainApp.java 的内容:
import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class MainApp {public static void main(String[] args) {ApplicationContext context =new ClassPathXmlApplicationContext("Beans.xml");HelloWorld obj = (HelloWorld) context.getBean("helloWorld");obj.getMessage();}}
第一步是我们使用框架 API ClassPathXmlApplicationContext() 来创建应用程序的上下文。这个 API 加载 beans 的配置文件并最终基于所提供的 API,它处理创建并初始化所有的对象,即在配置文件中提到的 beans。
第二步是使用已创建的上下文的 getBean() 方法来获得所需的 bean。这个方法使用 bean 的 ID 返回一个最终可以转换为实际对象的通用对象。一旦有了对象,你就可以使用这个对象调用任何类的方法。
bean作用域
<bean id="hello" name="hahaha" class="com.zhiyou100.spring.ioc.HelloWord" scope="prototype">
singleton:默认值 ,单例模式,在整个Spring IoC容器中,使用singleton定义的Bean将只有一个实例
prototype:原型模式,每次通过容器的getBean方法获取prototype定义的Bean时,都将产生一个新的Bean实例
request:对于每次HTTP请求,使用request定义的Bean都将产生一个新实例,即每次HTTP请求将会产生不同的Bean实例。只有在Web应用中使用Spring时,该作用域才有效
session:,表示每个会话需要容器创建一个全新 Bean。比如对于每个用户一般会有一个会话,该用户的用户信息需要存储到会话中,此时可以将该 Bean 配置为 web 作用域。
globalsession:每个全局的HTTP Session,使用session定义的Bean都将产生一个新实例。典型情况下,仅在使用portlet context的时候有效。同样只有在Web应用中使用Spring时,该作用域才有效
注解
@Runwith(SpringJUnit4ClassRunner.class) 将处理交给Spring管理
@Contextconfigruation 用来指定加载的Spring配置文件的位置,会加载默认配置文件
@AutoWired 属性注入
@Resource java自带属性注入
注入
属性注入
1. 构造器注入
<constructor-arg name=" name " value="张三">
2.setter注入
<bean id = "user" class="com.zhiyou100.demo1.User"><property name ="name" value="zhangsan"/><property name="age" value="18"/><property name="type" ref="type"/></bean>
p名称空间注入
<bean id= "user1" class="com.zhiyou100.demo1.User" p:age="19" p:name="李四" p:type-ref="type"/>
- 接口注入
复杂注入
<property name ="set"><set>< value="1"></set></property>
引用型注入 ref bean
<bean id = "user" class="com.zhiyou100.demo1.User"><property name ="name" value="zhangsan"/><property name="age" value="18"/><property name="type" ref="type"/></bean><bean id="type" class="com.zhiyou100.demo1.WorkType"><property name="name" value="学生"/></bean>
Bean实例化
1.构造器实例化
2. 静态工厂实例化、
3. 实例工厂实例化
实例工厂方式, 就是里面的getBean 方法不是静态的,也就是代表要先实例1个工厂对象, 才能依靠这个工厂对象去获得bean 对象。
数据库应用
XML 数据库配置
//加载资源<context:property-placeholder location="classpath:db.properties"/><!-- 配置数据源对象 --><bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/><property name="url" value="${jdbc.url}"/><property name="driverClassName" value="${jdbc.driver}"/></bean><bean id="template" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"> </property>
UserDao.java
方法的接口
public interface UserDao {void add(String name, String password,String phone);void delete(int id);void update(int id,String name, String password,String phone);UserBean query(int id);List<UserBean> list();}
UserDaoimpl.java
实现UserDao方法操作
public class UserDaoImpl implements UserDao {@Autowiredprivate DataSource dataSoure;//得到数据库的操作实例@AutowiredJdbcTemplate templete ;public void add(String name, String password, String phone) {templete.execute("insert into user (name,password,phone)values('"+name+"','"+password+"','"+phone+"')");}@Overridepublic void delete(int id) {templete.execute("delete from user where id= "+id);}@Overridepublic void update(int id, String name, String password, String phone) {String sql ="update user set name =? ,password=? ,phone=? where id = ?";templete.update(sql ,name,password,phone,id);}@Overridepublic UserBean query(int id) {String sql = "select * from user where id="+id;return templete.query(sql, new ResultSetExtractor<UserBean>() {@Overridepublic UserBean extractData(ResultSet rs) throws SQLException, DataAccessException {if(rs.next()) {UserBean user = new UserBean();user.setId(rs.getInt(1));user.setName(rs.getString(2));user.setPassword(rs.getString(3));user.setPhone(rs.getString(4));return user;}return null;}});}@Overridepublic List<UserBean> list() {String sql ="select * from user " ;return templete.query(sql , new RowMapper<UserBean>() {@Overridepublic UserBean mapRow(ResultSet rs, int rows) throws SQLException {System.out.println(rows);UserBean user = new UserBean();user.setId(rs.getInt(1));user.setName(rs.getString(2));user.setPassword(rs.getString(3));user.setPhone(rs.getString(4));return user;}});}}
获取Bean
public class BeanUtil {private static ApplicationContext appc = new ClassPathXmlApplicationContext("applicationContext.xml");public static Object getBean(String name) {return appc.getBean(name);}}
对象User
TestSpring
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfigurationpublic class TestSprin {@Autowiredprivate ApplicationContext appc;@Autowiredprivate UserBean user1;@Resourceprivate UserDao userDao1;@Testpublic void getUser() {System.out.println(user1);}@Testpublic void excuteAdd() {userDao1.add("张三", "12345", "1234445");//userDao.delete(1);//System.out.println(userDao.query(2));//System.out.println(userDao.list());userDao1.update(2, "陈涛1234", "112","112345");}}
