Spring(二)

一、目录结构

Spring(二)

二、代码

1、JdbcConfig

 

 1 package cn.bijian.config;
 2 
 3 import com.mchange.v2.c3p0.ComboPooledDataSource;
 4 import org.apache.commons.dbutils.QueryRunner;
 5 import org.springframework.beans.factory.annotation.Qualifier;
 6 import org.springframework.beans.factory.annotation.Value;
 7 import org.springframework.context.annotation.Bean;
 8 import org.springframework.context.annotation.Configuration;
 9 import org.springframework.context.annotation.Scope;
10 
11 import javax.sql.DataSource;
12 
13 //@Configuration
14 public class JdbcConfig {
15     @Value("${jdbc.driver}")
16     private String driver;
17     @Value("${jdbc.url}")
18     private String url;
19     @Value("${jdbc.username}")
20     private String username;
21     @Value("${jdbc.password}")
22     private String password;
23 
24     @Bean("runner") //作用:把当前方法的返回值作为bean对象存入spring的IOC容器中
25     @Scope("prototype")
26 //    public QueryRunner createQueryRunner(DataSource dataSource){
27 //        return new QueryRunner(dataSource);
28 //    }
29     public QueryRunner createQueryRunner(@Qualifier("datasource2") DataSource dataSource){
30         return new QueryRunner(dataSource);
31     }
32 
33 //    @Bean("datasource") //一个datasource的时候
34     @Bean("datasource2")
35     public DataSource createDataSource(){
36         try{
37             ComboPooledDataSource ds = new ComboPooledDataSource();
38             ds.setDriverClass(driver);
39             ds.setJdbcUrl(url);
40             ds.setUser(username);
41             ds.setPassword(password);
42             return ds;
43         }catch (Exception e){
44             throw new RuntimeException(e);
45         }
46     }
47 
48 
49     @Bean("datasource1")
50     public DataSource createDataSource1(){
51         try{
52             ComboPooledDataSource ds = new ComboPooledDataSource();
53             ds.setDriverClass(driver);
54             ds.setJdbcUrl("jdbc:mysql://localhost:3306/spring_1?serverTimezone=UTC");
55             ds.setUser(username);
56             ds.setPassword(password);
57             return ds;
58         }catch (Exception e){
59             throw new RuntimeException(e);
60         }
61     }
62 }

2、SpringConfiguration

 1 package cn.bijian.config;
 2 
 3 import com.mchange.v2.c3p0.ComboPooledDataSource;
 4 import org.apache.commons.dbutils.QueryRunner;
 5 import org.springframework.context.annotation.*;
 6 
 7 import javax.sql.DataSource;
 8 
 9 /*
10     配置类,作用同bean.xml
11  */
12 @Configuration //当使用AnnotationConfigApplicationContext时可以不写
13 //@ComponentScans({@ComponentScan("cn.bijian.dao"),@ComponentScan("cn.bijian.service")})
14 @ComponentScan(basePackages = "cn.bijian")
15 @PropertySource("classpath:jdbcConfig.properties")  //加载.properties文件中的配置
16 @Import({JdbcConfig.class})  //子配置
17 public class SpringConfiguration {
18 //    @Bean("runner")
19 //    @Scope("prototype")
20 //    public QueryRunner createQueryRunner(DataSource dataSource){
21 //        return new QueryRunner(dataSource);
22 //    }
23 //    @Bean("dataSource")
24 //    public DataSource createDataSource(){
25 //        try {
26 //            ComboPooledDataSource dataSource = new ComboPooledDataSource();
27 //            dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
28 //            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/spring?serverTimezone=UTC");
29 //            dataSource.setUser("root");
30 //            dataSource.setPassword("123456");
31 //            return dataSource;
32 //        }catch (Exception e){
33 //            throw new RuntimeException(e);
34 //        }
35 //    }
36 }

3、AccountDaoImpl

 1 package cn.bijian.dao.impl;
 2 
 3 import cn.bijian.dao.AccountDao;
 4 import cn.bijian.model.Account;
 5 import org.apache.commons.dbutils.QueryRunner;
 6 import org.apache.commons.dbutils.handlers.BeanHandler;
 7 import org.apache.commons.dbutils.handlers.BeanListHandler;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.stereotype.Repository;
10 
11 import java.util.List;
12 
13 @Repository("accountDao1")
14 public class AccountDaoImpl implements AccountDao {
15     @Autowired
16     private QueryRunner runner;
17 
18 //    public void setRunner(QueryRunner runner) {
19 //        this.runner = runner;
20 //    }
21 
22     @Override
23     public void saveAccount_test() {
24         System.out.println("账户保存了1111111!");
25     }
26 
27     @Override
28     public void saveAccount(Account account) {
29         try{
30             runner.update("insert into account(name,money) values (?,?)",account.getName(),account.getMoney());
31         }catch (Exception e){
32             throw new RuntimeException(e);
33         }
34     }
35 
36     @Override
37     public void deleteAccount(Integer id) {
38         try{
39             runner.update("delete from account where id = ?",id);
40         }catch (Exception e){
41             throw new RuntimeException(e);
42         }
43     }
44 
45     @Override
46     public void updateAccount(Account account) {
47         try{
48             runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
49         }catch (Exception e){
50             throw new RuntimeException(e);
51         }
52     }
53 
54     @Override
55     public Account findById(Integer id) {
56         try{
57             return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),id);
58         }catch (Exception e){
59             throw new RuntimeException(e);
60         }
61     }
62 
63     @Override
64     public List<Account> findAll() {
65         try{
66             return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
67         }catch (Exception e){
68             throw new RuntimeException(e);
69         }
70     }
71 }

4、AccountDaoImpl2

 1 package cn.bijian.dao.impl;
 2 
 3 import cn.bijian.dao.AccountDao;
 4 import cn.bijian.model.Account;
 5 import org.springframework.stereotype.Repository;
 6 
 7 import java.util.List;
 8 
 9 @Repository("accountDao2")
10 public class AccountDaoImpl2 implements AccountDao {
11 
12     @Override
13     public void saveAccount_test() {
14         System.out.println("账户保存了222222!");
15     }
16 
17     @Override
18     public void saveAccount(Account account) {
19 
20     }
21 
22     @Override
23     public void deleteAccount(Integer id) {
24 
25     }
26 
27     @Override
28     public void updateAccount(Account account) {
29 
30     }
31 
32     @Override
33     public Account findById(Integer id) {
34         return null;
35     }
36 
37     @Override
38     public List<Account> findAll() {
39         return null;
40     }
41 }

5、AccountDao

 1 package cn.bijian.dao;
 2 
 3 import cn.bijian.model.Account;
 4 
 5 import java.util.List;
 6 
 7 public interface AccountDao {
 8     void saveAccount_test();
 9 
10     void saveAccount(Account account);
11 
12     void deleteAccount(Integer id);
13 
14     void updateAccount(Account account);
15 
16     Account findById(Integer id);
17 
18     List<Account> findAll();
19 }

6、Account

 1 package cn.bijian.model;
 2 
 3 public class Account {
 4     private Integer id;
 5     private String name;
 6     private Double money;
 7 
 8     public Integer getId() {
 9         return id;
10     }
11 
12     public void setId(Integer id) {
13         this.id = id;
14     }
15 
16     public String getName() {
17         return name;
18     }
19 
20     public void setName(String name) {
21         this.name = name;
22     }
23 
24     public Double getMoney() {
25         return money;
26     }
27 
28     public void setMoney(Double money) {
29         this.money = money;
30     }
31 
32     @Override
33     public String toString() {
34         return "Account{" +
35                 "id=" + id +
36                 ", name='" + name + '\'' +
37                 ", money=" + money +
38                 '}';
39     }
40 }

7、AccountServiceImpl

 1 package cn.bijian.service.impl;
 2 
 3 import cn.bijian.dao.AccountDao;
 4 import cn.bijian.model.Account;
 5 import cn.bijian.service.AccountService;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.beans.factory.annotation.Qualifier;
 8 import org.springframework.context.annotation.Scope;
 9 import org.springframework.stereotype.Service;
10 
11 import javax.annotation.Resource;
12 import java.util.List;
13 
14 /*
15 知识点1:
16 @Scope("prototype"):
17     AccountService accountService1 = (AccountService)ac.getBean("accountService");
18     AccountService accountService2 = (AccountService)ac.getBean("accountService");
19     accountService1与accountService2   -> false
20 知识点2:
21     @PostConstruct:指定初始化方法
22     @PreDestroy:指定销毁方法
23  */
24 @Service("accountService")
25 //@Scope("prototype")
26 public class AccountServiceImpl implements AccountService {
27     @Autowired  //类型注入
28     @Qualifier("accountDao1") //类型注入的基础上按照id注入
29 //    @Resource(name = "accountDao2")  //直接按照id注入
30     private AccountDao accountDao;
31 
32 //    public void setAccountDao(AccountDao accountDao) {
33 //        this.accountDao = accountDao;
34 //    }
35 
36     @Override
37     public void saveAccount_test() {
38         accountDao.saveAccount_test();
39     }
40 
41     @Override
42     public void saveAccount(Account account) {
43         accountDao.saveAccount(account);
44     }
45 
46     @Override
47     public void deleteAccount(Integer id) {
48         accountDao.deleteAccount(id);
49     }
50 
51     @Override
52     public void updateAccount(Account account) {
53         accountDao.updateAccount(account);
54     }
55 
56     @Override
57     public Account findById(Integer id) {
58         return accountDao.findById(id);
59     }
60 
61     @Override
62     public List<Account> findAll() {
63         return accountDao.findAll();
64     }
65     
66 }

8、AccountService

 

 1 package cn.bijian.service;
 2 
 3 import cn.bijian.model.Account;
 4 
 5 import java.util.List;
 6 
 7 public interface AccountService {
 8     void saveAccount_test();
 9 
10     void saveAccount(Account account);
11 
12     void deleteAccount(Integer id);
13 
14     void updateAccount(Account account);
15 
16     Account findById(Integer id);
17 
18     List<Account> findAll();
19 }

9、Client

 1 package cn.bijian.ui;
 2 
 3 import cn.bijian.service.AccountService;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 
 7 public class Client {
 8     public static void main(String[] args) {
 9         ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
10         AccountService accountService = (AccountService)ac.getBean("accountService");
11         accountService.saveAccount_test();
12     }
13 }

10、AccountServiceTest

 1 package cn.bijian.test;
 2 
 3 import cn.bijian.model.Account;
 4 import cn.bijian.service.AccountService;
 5 import org.junit.Test;
 6 import org.springframework.context.ApplicationContext;
 7 import org.springframework.context.support.ClassPathXmlApplicationContext;
 8 
 9 import java.util.List;
10 
11 /*
12     使用xml配置文件的测试
13  */
14 public class AccountServiceTest {
15 
16     @Test
17     public void testSaveAccount() {
18         ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
19         AccountService accountService = ac.getBean("accountService", AccountService.class);
20         Account account = new Account();
21         account.setName("ddd");
22         account.setMoney(2000d);
23         accountService.saveAccount(account);
24     }
25 
26     @Test
27     public void testDeleteAccount(){
28         ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
29         AccountService accountService = ac.getBean("accountService", AccountService.class);
30         accountService.deleteAccount(12);
31     }
32 
33     @Test
34     public void testUpdateAccount(){
35         ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
36         AccountService accountService = ac.getBean("accountService", AccountService.class);
37         Account account = accountService.findById(3);
38         account.setName("ccc");
39         accountService.updateAccount(account);
40     }
41 
42     @Test
43     public void testFindById(){
44         ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
45         AccountService as = ac.getBean("accountService", AccountService.class);
46         Account account = as.findById(3);
47         System.out.println(account);
48     }
49 
50     @Test
51     public void testFindAll(){
52         ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
53         AccountService as = ac.getBean("accountService", AccountService.class);
54         List<Account> accounts = as.findAll();
55         for (Account account:accounts) {
56             System.out.println(account);
57         }
58     }
59 }

11、AccountServiceTest2

 1 package cn.bijian.test;
 2 
 3 import cn.bijian.config.SpringConfiguration;
 4 import cn.bijian.model.Account;
 5 import cn.bijian.service.AccountService;
 6 import org.junit.Test;
 7 import org.junit.runner.RunWith;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.context.ApplicationContext;
10 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
11 import org.springframework.test.context.ContextConfiguration;
12 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13 
14 import java.util.List;
15 /*
16     使用注解的测试
17  */
18 //测试spring的@autowired获取对象,要使用spring-test的测试,普通的junit无法获取bean,会报空指针,加上如下就可以获取到bean
19 @RunWith(SpringJUnit4ClassRunner.class)
20 @ContextConfiguration(classes = SpringConfiguration.class)
21 //@ContextConfiguration(locations= {"classpath:bean.xml"})
22 /*
23 @ContextConfiguration 注解:
24     locations 属性:用于指定配置文件的位置。如果是类路径下,需要用 classpath:表明
25         @ContextConfiguration(locations= {"classpath:bean.xml"})
26     classes 属性:用于指定注解的类。当不使用xml配置时,需要用此属性指定注解类的位置。
27         @ContextConfiguration(classes = SpringConfiguration.class)
28  */
29 public class AccountServiceTest2 {
30     @Autowired
31     private AccountService accountService;
32 
33     @Test
34     public void testSaveAccount() {
35 //        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
36         Account account = new Account();
37         account.setName("ddd");
38         account.setMoney(2000d);
39         accountService.saveAccount(account);
40     }
41 
42     @Test
43     public void testDeleteAccount(){
44         accountService.deleteAccount(12);
45     }
46 
47     @Test
48     public void testUpdateAccount(){
49         Account account = accountService.findById(3);
50         account.setName("ccc");
51         accountService.updateAccount(account);
52     }
53 
54     @Test
55     public void testFindById(){
56         Account account = accountService.findById(3);
57         System.out.println(account);
58     }
59 
60     @Test
61     public void testFindAll(){
62         List<Account> accounts = accountService.findAll();
63         for (Account account:accounts) {
64             System.out.println(account);
65         }
66     }
67 }

12、bean.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xsi:schemaLocation="http://www.springframework.org/schema/beans
 6         http://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/context
 8         http://www.springframework.org/schema/context/spring-context.xsd">
 9     <!--!!!!!!!!!!!!!!!!!!!!!基于注解注入!!!!!!!!!!!!!!!!!!!!!!!-->
10     <!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个名称为context名称空间和约束中-->
11     <context:component-scan base-package="cn.bijian.dao"></context:component-scan>
12     <context:component-scan base-package="cn.bijian.service"></context:component-scan>
13     <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
14         <constructor-arg name="ds" ref="dataSource"></constructor-arg>
15     </bean>
16     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
17         <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
18         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?serverTimezone=UTC"/>
19         <property name="user" value="root"/>
20         <property name="password" value="123456"/>
21     </bean>
22 
23     <!--!!!!!!!!!!!!!!!!!!!!!基于xml配置注入!!!!!!!!!!!!!!!!!!!!!!!-->
24 <!--    <bean id="accountService" class="cn.bijian.service.impl.AccountServiceImpl">-->
25 <!--        <property name="accountDao" ref="accountDao"></property>-->
26 <!--    </bean>-->
27 <!--    <bean id="accountDao" class="cn.bijian.dao.impl.AccountDaoImpl">-->
28 <!--        <property name="runner" ref="runner"></property>-->
29 <!--    </bean>-->
30 <!--    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">-->
31 <!--        <constructor-arg name="ds" ref="dataSource"></constructor-arg>-->
32 <!--    </bean>-->
33 <!--    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
34 <!--        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>-->
35 <!--        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?serverTimezone=UTC"/>-->
36 <!--        <property name="user" value="root"/>-->
37 <!--        <property name="password" value="123456"/>-->
38 <!--    </bean>-->
39 
40 </beans>

13、jdbcConfig.properties

jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/spring?serverTimezone=UTC
jdbc.username = root
jdbc.password = 123456

14、pom.xml

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 
  3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5   <modelVersion>4.0.0</modelVersion>
  6 
  7   <groupId>cn.bijian</groupId>
  8   <artifactId>Spring_review_2</artifactId>
  9   <version>1.0-SNAPSHOT</version>
 10 
 11   <name>Spring_review_2</name>
 12   <!-- FIXME change it to the project's website -->
 13   <url>http://www.example.com</url>
 14 
 15   <properties>
 16     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 17     <maven.compiler.source>1.7</maven.compiler.source>
 18     <maven.compiler.target>1.7</maven.compiler.target>
 19   </properties>
 20 
 21   <dependencies>
 22     <dependency>
 23       <groupId>org.mybatis</groupId>
 24       <artifactId>mybatis</artifactId>
 25       <version>3.5.6</version>
 26     </dependency>
 27 
 28     <dependency>
 29       <groupId>mysql</groupId>
 30       <artifactId>mysql-connector-java</artifactId>
 31       <version>8.0.21</version>
 32     </dependency>
 33 
 34     <dependency>
 35       <groupId>log4j</groupId>
 36       <artifactId>log4j</artifactId>
 37       <version>1.2.17</version>
 38     </dependency>
 39 
 40     <dependency>
 41       <groupId>junit</groupId>
 42       <artifactId>junit</artifactId>
 43       <version>4.12</version>
 44       <scope>test</scope>
 45     </dependency>
 46 
 47     <dependency>
 48       <groupId>org.apache.tomcat.maven</groupId>
 49       <artifactId>tomcat7-maven-plugin</artifactId>
 50       <version>2.2</version>
 51     </dependency>
 52 
 53     <dependency>
 54       <groupId>org.slf4j</groupId>
 55       <artifactId>slf4j-log4j12</artifactId>
 56       <version>1.6.6</version>
 57     </dependency>
 58 
 59     <dependency>
 60       <groupId>dom4j</groupId>
 61       <artifactId>dom4j</artifactId>
 62       <version>1.6.1</version>
 63     </dependency>
 64 
 65     <dependency>
 66       <groupId>jaxen</groupId>
 67       <artifactId>jaxen</artifactId>
 68       <version>1.1.6</version>
 69     </dependency>
 70 
 71     <dependency>
 72       <groupId>org.springframework</groupId>
 73       <artifactId>spring-context</artifactId>
 74       <version>5.0.3.RELEASE</version>
 75     </dependency>
 76 
 77     <dependency>
 78       <groupId>c3p0</groupId>
 79       <artifactId>c3p0</artifactId>
 80       <version>0.9.1.2</version>
 81     </dependency>
 82 
 83     <dependency>
 84       <groupId>commons-dbutils</groupId>
 85       <artifactId>commons-dbutils</artifactId>
 86       <version>1.7</version>
 87     </dependency>
 88 
 89     <dependency>
 90       <groupId>org.springframework</groupId>
 91       <artifactId>spring-test</artifactId>
 92       <version>5.0.2.RELEASE</version>
 93     </dependency>
 94 
 95     <dependency>
 96       <groupId>org.springframework</groupId>
 97       <artifactId>spring-aop</artifactId>
 98       <version>5.2.14.RELEASE</version>
 99     </dependency>
100   </dependencies>
101 
102 </project>

 

上一篇:Spring(三)


下一篇:SpringBoot + WebSocket 实现信息发送