Spring框架的学习

 

依赖包

主要依赖包

spring-beans   spring-context 

spring-core  spring-expression

applicationContext.xml 的配置文件

<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 name="user" class="com.test.web.bean.User">
        <property name="id" value="1"/>
        <property name="userName" value="sunming"/>
        <property name="passWord" value="root"/>
    </bean>
</beans>

spring 主要是提供一个容器

DI:依赖注入

注入的方式

 set 注入  构造注入  属性注入

注入类型

基本数据类型

ref 引用类型

IOC:又称控制反转,这里的反转是指,未使用spring 框架之前我们获取对象是通过new 的方式,而在使用spring 框架后,对象的获取是通过Spring 来获取的。这边的控制是指,spring 帮助我们控制new 对象的生命周期。这种技术是得益于依赖注入的应用

 

Web 应用的依赖关系

默认使用空参的构造方法来创建对象,在applicationContext.xml 文件中配置的bean 对象,在ApplicationContext 对象创建的时候,会被全部构造出来。可以用延迟加载这些对象

使用lazy-init 延迟加载,默认是default,这样只有在获取bean 对象的时候才会加载

<bean name="user" class="com.test.web.bean.User" lazy-init="true">

scope 属性:单例,或者多例

<bean name="user" class="com.test.web.bean.User" lazy-init="true" scope="singleton">

init-method 构造方法之后执行的方法

<bean name="user" class="com.test.web.bean.User" lazy-init="true" scope="prototype" init-method="init">

destory-method 容器销毁后执行的方法,但是scope 为多例的时候,就不会调用destory-method 指定的方法了

<bean name="user" class="com.test.web.bean.User" lazy-init="true" scope="prototype" init-method="init" dest
roy-method="destory">
set 方式注入,User类必须提供set get 方法,可以没有该属性
<bean name="user" class="com.test.web.bean.User" lazy-init="true" scope="prototype" init-method="init" destroy-method="destory">
    <property name="id" value="1"/>
    <property name="userName" value="sunming"/>
    <property name="passWord" value="root"/>

 

<!--引用类型注入 通过ref-->
<bean name="user" class="com.test.web.bean.User">
    <property name="id" value="1"/>
    <property name="userName" value="sunming"/>
    <property name="passWord" value="root"/>
    <property name="myPet" ref="pet"/>
</bean>
<bean name="pet" class="com.test.web.bean.Pet">
    <property name="name" value="dog"/>
    <property name="color" value="white"/>
</bean>
<!--构造注入-->
<bean name="myuser" class="com.test.web.bean.User">
    <constructor-arg name="id" value="2"/>
    <constructor-arg name="userName" value="sunming"/>
</bean>
指定参数类型
<!--构造注入-->
<bean name="myuser" class="com.test.web.bean.User">
    <constructor-arg name="id" value="2" type="java.lang.Integer"/>
    <constructor-arg name="userName" value="sunming"/>
</bean>
<!--构造注入 type 指定参数的类型 index 指定参数的位置-->
<bean name="myuser" class="com.test.web.bean.User">
    <constructor-arg name="id" value="2" type="java.lang.Integer" index="0"/>
    <constructor-arg name="userName" value="sunming"/>
</bean>
<!--复杂类型注入-->
<bean name="mycollection" class="com.test.web.bean.MyCollection">
    <!--array 属性注入-->
    <property name="array">
        <array>
            <value>123</value>
            <value>wewe</value>
            <ref bean="pet"/>
        </array>
    </property>
    <property name="list">
        <list>
            <value>4545</value>
            <value>drtrt</value>
            <ref bean="pet"/>
        </list>
    </property>
    <property name="set">
        <set>
            <value>99</value>
            <value>rrr</value>
            <ref bean="pet"/>
        </set>
    </property>
    <property name="map">
        <map>
            <entry key="123" value="123"/>
            <entry key-ref="pet" value-ref="pet"/>
        </map>
    </property>

    <property name="properties">
        <props>
            <prop key="name">老王</prop>
            <prop key="age">23</prop>
        </props>
    </property>
</bean>

注解,要使用AOP的包

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--使用注解开发-->
    <!--开启组件扫描 及子包的注解扫描-->
    <context:component-scan base-package="com.test.web.bean"/>
</beans>
package com.test.web.bean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

//@Scope(scopeName = "prototype")
@Component("user2_2")//早期使用的注解方式
///@Controller()//用于controlller注解
//@Service()//用于service 层注解
//@Repository()//用于dao 层注解

public class User2 {

    private String name;
    @Value("1")
    private Integer id;

    private Pet2 myPet;

    public Pet2 getMyPet() {
        return myPet;
    }
    //当有多个的时候,通过resource 指定
    @Resource(name = "pet2")
    //自动装配,容器中只有一个Pet2 的bean 时,可以使用
    //@Autowired
    public void setMyPet(Pet2 myPet) {
        this.myPet = myPet;
    }

    public String getName() {
        return name;
    }
    @Value("laowang")
    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public User2(){
        System.out.println("from user2");
    }
    //构造方法方法后调用
    @PostConstruct()
    public void userinit(){
        System.out.println("userinit");
    }
    //在ApplicationContext close 后调用
    @PreDestroy()
    public void userDestory(){
        System.out.println("userDestory");
    }

    @Override
    public String toString() {
        return "User2{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", myPet=" + myPet +
                '}';
    }
}

 使用SpringJunit 测试包

 

import com.test.web.bean.Pet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJunitTest {
    @Resource(name="pet")
    Pet pet;
    @Test
    public void test1(){
        System.out.println(pet.toString());
    }
}

分包配置applicationContext.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">
    <import resource="applicationContext_aop.xml"/>
</beans>

 简单使用

http://localhost:8080/spring_web/ :spring_web 为项目名称

c3p0-0.9.5.2.jar

mchange-commons-java-0.2.11.jar:c3p0 的辅助包,没有这个包会报错

mysql-connector-java-5.1.46-bin.jar:mysql 数据库驱动

ojdbc7.jar:oracle 的数据库驱动

分别创建web service dao bean 等层

@WebServlet("/UserLoginServlet")
public class UserLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doPost");
        //接收表单数据
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        //封装成User3 对象
        User3 tempUser=new User3();
        tempUser.setUsername(username);
        tempUser.setPassword(password);
        //调用service 层处理
        UserService userService=new UserServiceImpl();
        User3 user3=userService.getUserByInfo(tempUser);
        //根据用户验证结果进行操作
        if(user3==null){
            request.setAttribute("errorMsg","用户名或密码错误");
            request.getRequestDispatcher("/login_page.jsp").forward(request,response);
        }else{
            HttpSession session=request.getSession();
            session.setAttribute("user",tempUser);
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
public class User3DaoImpl implements User3Dao {

    private static ComboPooledDataSource dataSource;
    static{
        //配置c3p0
        try {
            dataSource=new ComboPooledDataSource();
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
            dataSource.setUser("root");
            dataSource.setPassword("root");
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    @Override
    public User3 getUserByInfo(User3 tempUser) {

        try {
            //通过数据库获取用户
            //连接数据库
            QueryRunner queryRunner=new QueryRunner(dataSource);
            String sql="select * from spring where username = ? and password = ?";
            return  queryRunner.query(sql,new BeanHandler<User3>(User3.class),tempUser.getUsername(),tempUser.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //使用dbutils 操作数据库
        return null;
    }
}

使用spring 来修改该项目

在applicationContext.xml 中配置项目

<!--配置datasource-->
<bean name="dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
    <property name="user" value="root"/>
    <property name="password" value="root"/>
</bean>
<!--配置dao-->
<bean name="userDao" class="com.test.web.dao.User3DaoImpl">
    <property name="dataSource" ref="dataSource"/>
</bean>
<!--配置service-->
<bean name="userService" class="com.test.web.service.UserServiceImpl">
    <property name="user3Dao" ref="userDao"/>
</bean>

 web.xml 添加项目监听

<!--配置监听器,在web 项目启动的时候,让spring 启动-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置spring 配置文件-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("doPost");
    //接收表单数据
    String username=request.getParameter("username");
    String password=request.getParameter("password");
    //封装成User3 对象
    User3 tempUser=new User3();
    tempUser.setUsername(username);
    tempUser.setPassword(password);
    //调用service 层处理
    //UserService userService=new UserServiceImpl();
    //User3 user3=userService.getUserByInfo(tempUser);
    //ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
    WebApplicationContext applicationContext= WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    userService=(UserServiceImpl)applicationContext.getBean("userService");
    User3 user3=userService.getUserByInfo(tempUser);


    //根据用户验证结果进行操作
    if(user3==null){
        request.setAttribute("errorMsg","用户名或密码错误");
        request.getRequestDispatcher("/login_page.jsp").forward(request,response);
    }else{
        HttpSession session=request.getSession();
        session.setAttribute("user",tempUser);
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }
}

 关于AOP 面向切面的思想

 

package com.test.aop.service;

public interface UserService {
    // 增
    void save();
    // 删
    void delete();
    // 改
    void update();
    // 查
    void find();
}
package com.test.aop.service;

public class UserServiceImpl implements UserService {

    @Override
    public void save() {
        System.out.println("save");
    }

    @Override
    public void delete() {
        System.out.println("delete");
    }

    @Override
    public void update() {
        System.out.println("update");
    }

    @Override
    public void find() {
        System.out.println("find");
    }
}

 

package com.test.aop.test;

import com.test.aop.service.UserService;
import com.test.aop.service.UserServiceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//动态代理增强类
public class UserServiceProxy {
    public UserService getUserServiceProxy(UserService userService){
        return (UserService) Proxy.newProxyInstance(UserServiceProxy.class.getClassLoader(), UserServiceImpl.class.getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("开启事务");
                Object invoke=method.invoke(userService,args);
                System.out.println("提交回滚");
                return null;
            }
        });
    }
}

从外部文件引入

D:\Project\src\db.properties

db.properties

jdbc.driverClass=com.mysql.jdbc.Driver;
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/spring
jdbc.user=root
jdbc.password=root

 applicationContext.xml 中配置

<!--加载外部配置-->
<context:property-placeholder location="db.properties"/>

<!--配置dataSource-->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driverClass}"/>
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
    <property name="user" value="${jdbc.user}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

 

 aop 配置的方式

<!--目标对象-->
<bean name="userService" class="com.test.aop.service.UserServiceImpl"/>
<!--通知对象-->
<bean name="myAdvice" class="com.test.aop.MyAdvice"/>
<aop:config>
    <!--切入点表达式,可以配置要增强的方法 id 为切入点唯一标识-->
    <aop:pointcut id="userservice" expression="execution(* com.test.aop.service.UserServiceImpl.*(..))"/>
    <!--切面 :切点加通知-->
    <aop:aspect ref="myAdvice">
        <aop:before method="before" pointcut-ref="userservice"/>
        <aop:after method="after" pointcut-ref="userservice"/>
        <aop:after-returning method="afterReturning" pointcut-ref="userservice"/>
    </aop:aspect>
</aop:config>

public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
    @Override
    public User getUserById(Integer id) {
        String sql="select * from spring where id = ?";
        return getJdbcTemplate().queryForObject(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user=new User();
                user.setId(resultSet.getInt(1));
                user.setPassword(resultSet.getString(2));
                user.setUsername(resultSet.getString(3));
                return user;
            }
        },id);
    }
}
  • < aop:aspect>:定义切面(切面包括通知和切点)
  • < aop:advisor>:定义通知器(通知器跟切面一样,也包括通知和切点
<!--配置事务核心管理器不同平台不一样-->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="transforAccount" isolation="DEFAULT" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>
<!--配置aop-->
<aop:config>
    <aop:pointcut id="txPc" expression="execution(* com.spring.jdbc.service.*ServiceImpl.*(..))"/>
    <aop:advisor advice-ref="txAdvice"  pointcut-ref="txPc"/>
</aop:config>
<!--开启注解事务-->
<tx:annotation-driven/>

 

使用注解配置事务
@Override
@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
public void transforAccount() {
    accountDao.addMoney(3,100);
    int i=1/0;
    accountDao.subMoney(2,100);
}
影响该类下所有方法
package com.spring.jdbc.service;

import com.spring.jdbc.dao.AccountDao;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
public class AccountServiceImpl implements AccountService {

    public AccountDao getAccountDao() {
        return accountDao;
    }

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    private AccountDao accountDao;

    @Override
    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
    public void transforAccount() {
        accountDao.addMoney(3,100);
        int i=1/0;
        accountDao.subMoney(2,100);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值