微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

spring示例--01

    主要内容:bean的装配

        ①完全的基于xml配置

        ②基于配置类的

        ③去掉xml,完全靠注解的

1. 准备工作

    1.1 数据准备:

CREATE TABLE `user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `birthday` datetime DEFAULT NULL,
  `sex` varchar(10) DEFAULT NULL,
  `address` varchar(40) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

 

INSERT INTO test.user (id, name, birthday, sex, address) VALUES (1, 'name1', '1995-01-01 00:00:00', 'man', 'address1');
INSERT INTO test.user (id, name, birthday, sex, address) VALUES (2, 'name2', '1995-01-01 00:00:00', 'man', 'address2');

 

    1.2 数据操作:使用JdbcTemplate,暂忽略事务控制

 

    1.3 maven包:全都是4.0.0版本

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${spring-context.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>${spring-core.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>${spring-beans.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-expression</artifactId>
  <version>${spring-expression.version}</version>
</dependency>
<!--spring aop-->
<!--    <dependency>-->
<!--      <groupId>org.springframework</groupId>-->
<!--      <artifactId>spring-aop</artifactId>-->
<!--      <version>${spring-aop.version}</version>-->
<!--    </dependency>-->
<!--spring jdbc-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>${spring-jdbc.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>${spring-tx.version}</version>
</dependency>

 

  1.4 实体类

package xt.domain;

import lombok.*;


@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class User {
    private Integer id;
    private String username;
    private String birthday;
    private String sex;
    private String address;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

 

 

2. 基于xml的

    Dao里面通过JdbcTemplate执行sql,JdbcTemplate通过xml配置装配(构造函数注入)到Dao上

package xt.demo.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import xt.domain.User;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.sqlException;
import java.util.List;

public class UserDao {
    private JdbcTemplate jt;  
    public UserDao(JdbcTemplate jt) {this.jt = jt;}
    
    public int saveUser(User user) {
        return jt.update("insert into user values(null,?,?,?,?)",new PreparedStatementSetter(){
            @Override
            public void setValues(PreparedStatement ps) throws sqlException {
                ps.setString(1,user.getUsername());
                ps.setString(2,user.getBirthday());
                ps.setString(3,user.getSex());
                ps.setString(4,user.getAddress());
            }
        });
    }

    public List<User> queryAllUser() {
        List<User> lists = jt.query("select * from user", new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws sqlException {
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setUsername(resultSet.getString("name"));
                user.setBirthday(resultSet.getString("birthday"));
                user.setSex(resultSet.getString("sex"));
                user.setAddress(resultSet.getString("address"));
                return user;
            }
        });
        return lists;
    }
}

 

    相应的配置文件:beanx.xml 放在Resources的一级目录下 

<?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="UserDao" class="xt.demo.dao.UserDao">
        <constructor-arg name="jt" ref="jdbcTemplate"/>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource1"></property>
    </bean>

    <!--数据源-->
    <bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.MysqL.jdbc.Driver" />
        <property name="url" value="jdbc:MysqL://127.0.0.1:3306/test?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf8"/>    <!--注意&符号写为 &amp;  否则解析配置文件会出错-->
        <property name="username" value="root"/>
        <property name="password" value="123"/>
    </bean>
</beans>

 

    测试:

ApplicationContext ac = new ClasspathXmlApplicationContext("beans.xml");
UserDao userDao = ac.getBean("UserDao", UserDao.class);
List<User> users = userDao.queryAllUser();

 

 

    基于xml装配特点:

         自由使用,比如自己写的Dao里面,要用到第三方库里的JdbcTemplate,在bean标签里面引用即可

         对象很多时,bean标签也多了起来;每个要获取bean里面的对象的地方,都要先读取xml返回ApplicationContext对象

 

3. 基于配置类

    配置类与业务逻辑无关,单独放在一个地方,只用来配置bean(通过java配置类装配而不是xml里的bean标签

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。