1. 程式人生 > >Spring使用與ssh整合

Spring使用與ssh整合

第一步導包

配置約束

在src下建立applicationContext.xml檔案

<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd "
>
</beans>

建立物件

<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd "
>
<!--將User交給spring管理--> <!--Bean元素:使用該元素描述需要spring容器管理的物件 name屬性:給被管理的物件七個名字,獲得物件時根據該名稱獲取物件,名稱可以使用,可以重複 class屬性:被管理物件的完整類名 id屬性:與name屬性一模一樣,名稱不可重複,不能使用特殊字元 儘量使用name--> <!--空參建立--> <!--scope: singleton(預設值):只會存在一個例項 prototype:每次都會建立 -->
<!-- init-method 建立好物件執行某個方法, destroy-mothod:銷燬物件會執行方法--> <bean name="user" class="com.fmt.spring.bean.User" init-method="init" destroy-method="destory"></bean> <!--靜態方法建立--> <bean name="user1" class="com.fmt.spring.bean.UserFactory" factory-method="createUser"></bean> <!--例項工程建立--> <bean name="userfactory" class="com.fmt.spring.bean.UserFactory" ></bean> <bean name="user2" factory-bean="userfactory" factory-method="createUser2"></bean> <!--匯入其他spring的配置檔案--> <import resource="com/fmt/spring/test/applicationContext.xml"></import> </beans>
public class User {
    private String name;
    private Integer age;

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    public void init(){
        System.out.println("init");
    }
    public void destory(){
        System.out.println("destory");
    }
}

public class UserFactory {
    public static User createUser(){
        return new User();
    }

    public  User createUser2(){
        return new User();
    }
}


 @Test
    public void fun1(){

        //1.建立容器
        ClassPathXmlApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
        //2.向容器要user物件(第一種)
        User user = (User) ac.getBean("user");
         //2.向容器要user物件(第二種)
        User user = (User) ac.getBean("user1");
         //2.向容器要user物件(第三種)
        User user = (User) ac.getBean("user2");
        //列印user
        System.out.println(user);
        //容器關閉
        ac.close();
    }

屬性注入

(set方法注入)
    <bean  name="user" class="com.fmt.spring.bean.User">
        <property name="name" value="tom"></property>
        <property name="age" value="19"></property>
        <property name="car" ref="car"></property>
    </bean>


    <bean name="car" class="com.fmt.spring.bean.Car">
        <property name="name" value="bwm"></property>
        <property name="color" value="red"></property>
    </bean>

建構函式注入
  <bean  name="user1" class="com.fmt.spring.bean.User">
       <constructor-arg name="name" value="tom"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="car" ref="car1"></constructor-arg>
    </bean>
    <bean name="car1" class="com.fmt.spring.bean.Car">

          <constructor-arg name="name" value="bwm" index="0"></constructor-arg>
        <constructor-arg name="color" value="red" index="1"></constructor-arg>
    </bean>

//為了避免有多個建構函式指定不了映入index和type
 <bean  name="user2" class="com.fmt.spring.bean.User">
        <!--name屬性:建構函式的引數名
             index屬性:建構函式的引數索引
             type屬性:建構函式的的引數型別-->
        <constructor-arg name="name" value="999" index="0" type="java.lang.Integer"></constructor-arg>
        <constructor-arg name="car" ref="car1" index="1"></constructor-arg>
    </bean>


 <!--p 名稱空間注入
     1.匯入p名稱空間 xmlns:p="http://www.springframework.org/schema/p"
     2.使用p:屬性完成注入
          -值型別:p:屬性名="值"
          -物件型別:p:屬性名-ref="bean名稱"
    -->
    <bean  name="user3" class="com.fmt.spring.bean.User" p:age="10" p:name="jack" p:car-ref="car">

    </bean>

 <!--
     spel注入:sprig Expression Language spring表示式語言

    -->
    <bean name="user4" class="com.fmt.spring.bean.User">
        <property name="name" value="#{user3.name}"></property>
        <property name="age" value="#{user3.age}"></property>
        <property name="car" ref="car"></property>
    </bean>


  <!--複雜型別注入-->
    <!--array注入-->
    <bean name="cb" class="com.fmt.spring.bean.CollectionBean">
        <!--如果陣列中只准備註入一個值直接使用value或ref-->
        <!--<property name="arr" value="tom"></property>-->
        <!--多個元素注入-->
        <property name="arr">
            <array>
                <value>tom</value>
                <value>jack</value>
                <ref bean="user4"></ref>
            </array>
        </property>

        <property name="list">
            <array>
                <value>1</value>
                <value>2</value>
                <ref bean="user4"></ref>
            </array>
        </property>

        <property name="map">
           <map>
               <entry key="url" value="www.baidu.com"></entry>
               <entry key="xka" value="顯示卡"></entry>
               <entry key-ref="user3" value-ref="user2"></entry>
           </map>
        </property>

        <property name="properties">
            <props>
                <prop key="bianma">utf-8</prop>
                <prop key="max">8m</prop>
            </props>
        </property>
    </bean>


public class User {
    private String name;
    private Integer age;
    private Car car;

    public User() {
        System.out.println("無參建構函式");
    }

    public User(String name, Integer age, Car car) {
        this.name = name;
        this.age = age;
        this.car = car;
    }
        public User(String name, Car car) {
        System.out.println("User(String name, Car car)!!");
        this.name = name;
        this.car = car;
    }

    public User(Car car,String name) {
        System.out.println("User(Car car,String name)!!");
        this.name = name;
        this.car = car;
    }

    public User(Integer name, Car car) {
        System.out.println("User(Integer name, Car car)!!");
        this.name = name+"";
        this.car = car;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public void setName(String name) {
        this.name = name;
    }
public void setCar(Car car) {
        this.car = car;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

public class Car {

    public String name;
    public String color;


    public Car() {
    }

    public Car(String name, String color) {
        this.name = name;
        this.color = color;
        System.out.println("car ");
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setColor(String color) {
        this.color = color;
    }


    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                '}';
    }
}

public class CollectionBean {
    private Object[] arr;
    private List list;
    private Map  map;
    private Properties properties;


    public Object[] getArr() {
        return arr;
    }

    public void setArr(Object[] arr) {
        this.arr = arr;
    }

    public List getList() {
        return list;
    }

    public void setList(List list) {
        this.list = list;
    }

    public Map getMap() {
        return map;
    }

    public void setMap(Map map) {
        this.map = map;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @Override
    public String toString() {
        return "CollectionBean{" +
                "arr=" + Arrays.toString(arr) +
                ", list=" + list +
                ", map=" + map +
                ", properties=" + properties +
                '}';
    }
}

    @Test
    public void fun4(){

        //1.建立容器
        ApplicationContext ac=new ClassPathXmlApplicationContext("com/fmt/spring/test/applicationContext.xml");
        //2.向容器要user物件
        User user = (User) ac.getBean("user");
        //列印user
        System.out.println(user);
    }

註解

註解是為了代替配置

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

    <!--
     指定掃描這個包下的所有類的註解
     掃描包下,會掃描指定包下的所有包
    -->
    <context:component-scan base-package="com.fmt.spring.aop">


    </context:component-scan>
    <bean name="car2" class="com.fmt.spring.aop.Car">
        <property name="name" value="蘭博基尼"></property>
        <property name="color" value="白色"></property>
    </bean>
</beans>
//<bean name="user" class="com.fmt.spring.bean.User/>
Component("user")
  @Service("user")//service層
  @Controller("user")//web層
  @Repository("user")//dao層
//指定物件的作用範圍
Scope(scopeName = "prototype")
public class User {
    @Value("tom")
    public String name;
    @Value("18")
    public Integer age;


    //自動裝配,如果碰到多個型別一直的物件,將無法選擇具體注入那個物件
    @Autowired
    public Car car;

//    @Qualifier("car2")//使用註解告訴spring容器,去取那個Car物件
//    public Car car2;


    @PostConstruct//物件被建立後,呼叫init-method
    public void init(){

    }
    @PreDestroy//物件即將被銷燬錢呼叫,destory-method
    public void destory(){

    }


    @Resource(name="car2")//手動注入,指定注入那個名稱的bean物件
    public Car car3;
    @Value("jack")
    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", car=" + car +
                ", car3=" + car3 +
                '}';
    }
}

使用spring與juit結合不用每次都建立容器直接使用

RunWith(SpringJUnit4ClassRunner.class)//幫我們建立容器
//指定建立容器時使用那個配置檔案
ContextConfiguration("classpath:com/fmt/spring/aop/applicationContext.xml")
public class Demo {

    @Resource(name="car2")
    private Car car;

    @Test
    public void fun1(){
        System.out.println(car);
    }
}

aop

public interface UserInterface {
    void save();
    void delete();
    void update();
    void find();
}

public class UserInterfaceImpl implements UserInterface {
    @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");
    }
}

public class MyAdvice {

    //前置通知:目標方法執行之前呼叫
    public void before(){
        System.out.println("前置通知");
    }
    //後置通知,如果方法出現異常不會呼叫
    public void afterReturn(){
        System.out.println("後置通知");
    }

    //環繞通知,方法之前之後都會呼叫
    public void around(ProceedingJoinPoint pjp){

        System.out.println("環繞通知之前的部分");
        try {
            pjp.proceed();//呼叫目標方法
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("這是後置通知(如果出現異常不會呼叫)!!");
    }
    //異常通知
    public void afterException(){
        System.out.println("異常時呼叫");
    }
    //後置通知出現異常也會呼叫
    public void after(){
        System.out.println("這是後置通知(出現異常也會呼叫)");
    }



}
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置目標物件-->
    <bean name="userServiceTarget" class="com.fmt.spring.service.UserInterfaceImpl">
    </bean>
    <!--配置通知物件-->
    <bean name="myAdvice" class="com.fmt.spring.service.MyAdvice">
    </bean>
    <!--配置將通知織入物件-->
    <aop:config>
        <!--配置切入點
        public void com.fmt.spring.service.UserInterfaceImpl.save()
        void com.fmt.spring.service.UserInterfaceImpl.save()
        * com.fmt.spring.service.UserInterfaceImpl.*()
        * com.fmt.spring.service.UserInterfaceImpl.*(..)
        * com.fmt.spring.service.*InterfaceImpl.*(..)
        * com.fmt.spring.service..*InterfaceImpl.*(..)
        -->
        <aop:pointcut id="pc" expression="execution(public void com.fmt.spring.service.UserInterfaceImpl.save())"></aop:pointcut>
        <!--指定敏給before作為前置通知,切入到pc這個方法中-->
        <aop:aspect ref="myAdvice">
            <aop:before method="before" pointcut-ref="pc"></aop:before>
            <!--後置-->
            <aop:after-returning method="afterReturn" pointcut-ref="pc"></aop:after-returning>
            <!--環繞-->
            <aop:around method="around" pointcut-ref="pc"></aop:around>
            <!--異常攔截通知-->
            <aop:after-throwing method="afterException" pointcut-ref="pc"></aop:after-throwing>
           <!--後置-->
            <aop:after method="after" pointcut-ref="pc"></aop:after>
        </aop:aspect    
        >
    </aop:config>
</beans>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:com/fmt/spring/springaop/applicationContext.xml")
public class DemoTest {

    @Resource(name= "userServiceTarget")
    private UserInterface us;


    @Test
    public void fun1(){
      us.save();
    }
}

註解配置

//通知類
@Aspect
//表示該類是通知類
public class MyAdvice {

    //前置通知:目標方法執行之前呼叫
    @Before("execution(* com.fmt.spring.service..*InterfaceImpl.*(..))")
    public void before(){
        System.out.println("前置通知");
    }
    //後置通知,如果方法出現異常不會呼叫
    @AfterReturning("execution(* com.fmt.spring.service..*InterfaceImpl.*(..))")
    public void afterReturn(){
        System.out.println("後置通知");
    }

    //環繞通知,方法之前之後都會呼叫
    @Around("execution(* com.fmt.spring.service..*InterfaceImpl.*(..))")
    public void around(ProceedingJoinPoint pjp){

        System.out.println("環繞通知之前的部分");
        try {
            pjp.proceed();//呼叫目標方法
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("這是後置通知(如果出現異常不會呼叫)!!");
    }
    //異常通知
    @AfterThrowing("execution(* com.fmt.spring.service..*InterfaceImpl.*(..))")
    public void afterException(){
        System.out.println("異常時呼叫");
    }
    //後置通知出現異常也會呼叫
    @After("execution(* com.fmt.spring.service..*InterfaceImpl.*(..))")
    public void after(){
        System.out.println("這是後置通知(出現異常也會呼叫)");
    }



}

在xml中只需要配置

   <!--配置目標物件-->
    <bean name="userServiceTarget" class="com.fmt.spring.service.UserInterfaceImpl">
    </bean>
    <!--配置通知物件-->
    <bean name="myAdvice" class="com.fmt.spring.service.MyAdvice">
    </bean>
    <!-- 開啟使用註解完成織入-->
    <aop:aspectj-autoproxy>

    </aop:aspectj-autoproxy>

JDBC

    @Test
    public void fun1(){
        //準備連線池

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        try {
            comboPooledDataSource.setDriverClass("com.jdbc.mysql.jdbc.Driver");
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        comboPooledDataSource.setJdbcUrl("jdbc:mysql:///jdbctest");
        comboPooledDataSource.setUser("root");
        comboPooledDataSource.setPassword("123456");

        //建立JDBC末班物件
        JdbcTemplate jt=new JdbcTemplate();

        jt.setDataSource(comboPooledDataSource);
        //書寫sql語句
        String sql="insert into t_user values(null,'rose')";
        jt.update(sql);
    }

xml配置

      <!--將連線池放到spring容器裡-->
   <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="jdbcUrl" value="jdbc:mysql:///jdbctest"></property>
       <property name="driverClass" value="com.jdbc.mysql.jdbc.Driver"></property>
       <property name="user" value="root"></property>
       <property name="password" value="123456"></property>
   </bean>


<!--將JDBCTemple放到spring容器裡-->
    <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--將UserDao放到spring容器了-->
     <bean name="userDao" class="com.fmt.spring.jdbc.UserDaoImp">
         <property name="jt" ref="jdbcTemplate"></property>
     </bean>
public class UserDaoImp implements UserDao {

    private JdbcTemplate jt;

    @Override
    public void save(User user) {
        String sql="insert into t_user values(null,?)";
        jt.update(sql,user.name);
    }

    @Override
    public void find(Integer id) {
        String sql="select * from t_user where id=?";
        jt.queryForObject(sql, (resultSet, i) -> {
            User user = new User();
            user.id=resultSet.getInt("id");
            user.name=resultSet.getString("name");
            return user;
        }, id);
    }

    @Override
    public void delete(Integer id) {
        String sql="delete from t_user where id=?";
        jt.update(sql,1);
    }

    @Override
    public void update(User user) {
        String sql="update  t_user set name=? where id=? ";
        jt.update(sql,user.name,user.id);
    }

    @Override
    public int getTotalCount() {
        String sql="select count(*) from t_user";
        Integer integer = jt.queryForObject(sql, Integer.class);
        return integer;
    }

    @Override
    public List<User> getUserAll() {
        String sql="select * from t_user";
        List<User> list = jt.query(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.id = resultSet.getInt("id");
                user.name = resultSet.getString("name");
                return user;
            }
        });
        return list;
    }

    public void setJt(JdbcTemplate jt) {
        this.jt = jt;
    }

    public JdbcTemplate getJt() {
        return jt;
    }
}
   @Test
    public void fun2(){
        //準備連線池

        User user = new User();
        user.name="xxx";
        userDao.delete(1);


    }

JdbcDaoSupport

public class UserDaoImp extends JdbcDaoSupport implements UserDao {


    @Override
    public void save(User user) {
        String sql="insert into t_user values(null,?)";
        super.getJdbcTemplate().update(sql,user.name);
    }

}
  <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="jdbcUrl" value="jdbc:mysql:///jdbctest"></property>
       <property name="driverClass" value="com.jdbc.mysql.jdbc.Driver"></property>
       <property name="user" value="root"></property>
       <property name="password" value="123456"></property>
   </bean>
   <!--將UserDao放到spring容器了-->
     <bean name="userDao" class="com.fmt.spring.jdbc.UserDaoImp">
         <property name="dataSource" ref="dataSource"></property>
     </bean>

讀取配置檔案

db.properties

jdbc.jdbcUrl=jdbc:mysql:///jdbctest
jdbc.driverClass=com.jdbc.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456
    <!--指定property 讀取配置檔案-->
    <context:property-placeholder location="classpath:com/fmt/spring/jdbc/db.properties">     </context:property-placeholder>
   <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
       <property name="driverClass" value="${jdbc.driverClass}"></property>
       <property name="user" value="${jdbc.user}"></property>
       <property name="password" value="${jdbc.password}"<