您现在的位置是:首页 > 编程 > 

【旧】G005Spring学习笔记

2025-07-25 22:23:05
【旧】G005Spring学习笔记 一、完全注解实现1、说明代码语言:javascript代码运行次数:0运行复制 * spring的新注解: * Configuration: * 作用:指定当前类是一个配置类; * ComponentScan: * 作用:指定spring在创建容器时要扫描的包; * 属性: * value:它和basePackages的作用是一致的,

【旧】G005Spring学习笔记

一、完全注解实现

1、说明

代码语言:javascript代码运行次数:0运行复制
 * spring的新注解:
 * Configuration:
 *  作用:指定当前类是一个配置类;
 * ComponentScan:
 *  作用:指定spring在创建容器时要扫描的包;
 *  属性:
 *      value:它和basePackages的作用是一致的,都是指定spring在创建容器时要扫描的包;
 *      备注:我们使用此注解就等同于在xml中配置:<context:component-scan base-package="com.zibo"/>
 * Bean:
 *  作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器;
 *  属性:name用于指定bean的id,当不写时,默认值为当前方法的名称;
 *  细节:当我们使用注解配置方法时,如果方法有参数,spring框架去容器中查有没有可用的bean对象;
 *       查的方式和Autowired注解的作用是一致的;

2、代码示例

SpringConfiguration类:
代码语言:javascript代码运行次数:0运行复制
package com.;

import ComboPooledDataSource;
import org.apachem.dbutils.QueryRunner;
import org.annotation.Bean;
import org.annotation.ComponentScan;
import org.annotation.Configuration;
import org.annotation.Scope;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * 该类是一个配置类,其作用于bean.xml相同
 * spring的新注解:
 * Configuration:
 *  作用:指定当前类是一个配置类;
 * ComponentScan:
 *  作用:指定spring在创建容器时要扫描的包;
 *  属性:
 *      value:它和basePackages的作用是一致的,都是指定spring在创建容器时要扫描的包;
 *      备注:我们使用此注解就等同于在xml中配置:<context:component-scan base-package="com.zibo"/>
 * Bean:
 *  作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器;
 *  属性:name用于指定bean的id,当不写时,默认值为当前方法的名称;
 *  细节:当我们使用注解配置方法时,如果方法有参数,spring框架去容器中查有没有可用的bean对象;
 *       查的方式和Autowired注解的作用是一致的;
 */
@Configuration
@ComponentScan(basePackages = "com.zibo")//可省略为@ComponentScan("com.zibo")
public class SpringConfiguration {
    //用于创建QueryRunner对象
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }
    //用于创建数据源对象
    @Bean(name = "dataSource")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass("jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:06/zibo?serverTimezone=UTC");
            ds.setUser("root");
            ds.setPassword("zibo1529417242");
            return ds;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }
}
AccountServiceTest类:
代码语言:javascript代码运行次数:0运行复制
package com.;

import com..SpringConfiguration;
import com.zibo.domain.Account;
import com.zibo.service.IAccountService;
import org.junit.Before;
import org.junit.Test;
import org.ApplicationContext;
import org.annotation.AnnotationConfigApplicationContext;
import org.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 使用junit单元测试进行测试
 */
public class AccountServiceTest {
    private ApplicationContext ac;
    private IAccountService as;
    @Before
    public void init(){
        //1、获取容器
//        ac = new ClassPathXmlApplicationContext("bean.xml");
        ac = new AnnotationConfigApplicationContext();
        //2、得到业务层对象
        as = ac.getBean("accountService", );
    }
    @Before
    public void end(){
//        ();
    }
    @Test
    public void testFindAllAccount(){
        //、执行方法
        List<Account> accounts = as.findAllAccount();
        //4、遍历输出
        for (Account account : accounts) {
            println(account);
        }
    }
    @Test
    public void testFindAccountById(){
        Account account = as.findAccountById(1);
        println(account);
    }
    @Test
    public void testSave(){
        Account account = new Account();
        account.setame("大哥");
        account.setMoney(2000);
        as.saveAccount(account);
    }
    @Test
    public void testUpdate(){
        Account account = new Account();
        account.setId();
        account.setame("二哥");
        account.setMoney(000);
        as.updateAccount(account);
    }
    @Test
    public void testDelete(){
        as.deleteAccountById(1);
    }
}
QueryRunnerTest类:
代码语言:javascript代码运行次数:0运行复制
package com.;

import com..SpringConfiguration;
import org.apachem.dbutils.QueryRunner;
import org.junit.Test;
import org.ApplicationContext;
import org.annotation.AnnotationConfigApplicationContext;

public class QueryRunnerTest {
    @Test
    public void testQueryRunnerTest(){
        ApplicationContext ac = new AnnotationConfigApplicationContext();
        QueryRunner runner1 = ac.getBean("runner", );
        QueryRunner runner2 = ac.getBean("runner", );
        println(runner1 == runner2);//true,由此可见,默认是单例,加注解@Scope("prototype")后边多例
    }
}
文件结构图:
其他文件:

见G004Spring学习笔记-IOC案例;

二、问题发现和解决

1、问题

截图:
说明:

配置信息写在代码里岂不是写死了,应该写在配置文件中;

优化后的代码:

SpringConfiguration配置类:

代码语言:javascript代码运行次数:0运行复制
package com.;

import ComboPooledDataSource;
import org.apachem.dbutils.QueryRunner;
import org.annotation.*;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * 该类是一个配置类,其作用于bean.xml相同
 * spring的新注解:
 * Configuration:
 *  作用:指定当前类是一个配置类;
 * ComponentScan:
 *  作用:指定spring在创建容器时要扫描的包;
 *  属性:
 *      value:它和basePackages的作用是一致的,都是指定spring在创建容器时要扫描的包;
 *      备注:我们使用此注解就等同于在xml中配置:<context:component-scan base-package="com.zibo"/>
 * Bean:
 *  作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器;
 *  属性:name用于指定bean的id,当不写时,默认值为当前方法的名称;
 *  细节:当我们使用注解配置方法时,如果方法有参数,spring框架去容器中查有没有可用的bean对象;
 *       查的方式和Autowired注解的作用是一致的;(可以手动指定@Qualifier("数据源名字"))
 * Import:
 *  作用:用于导入其他的配置类;
 *  属性:value用于指定其他配置类的字节码,当我们使用Import注解的时候,有Import注解的类是父配置类,
 *  导入的类是子配置类;
 *
 *  PropertySource:
 *  作用:用于指定properties文件的位置;
 *  属性:value指定文件的名称和路径,关键字classpath表示类路径下
 */
@Configuration
@ComponentScan(basePackages = "com.zibo")//可省略为@ComponentScan("com.zibo")
@Import()
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {

}

JdbcConfig类:

代码语言:javascript代码运行次数:0运行复制
package com.;

import ComboPooledDataSource;
import org.apachem.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Value;
import org.annotation.Bean;
import org.annotation.ComponentScan;
import org.annotation.Configuration;
import org.annotation.Scope;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@Configuration
@ComponentScan(basePackages = "com.zibo")//可省略为@ComponentScan("com.zibo")
public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    //用于创建QueryRunner对象
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }
    //用于创建数据源对象
    @Bean(name = "dataSource")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }
}
jdbcConfig.properties配置文件:
代码语言:javascript代码运行次数:0运行复制
jdbc.driver=jdbc.Driver
jdbc.url=jdbc:mysql://localhost:06/zibo?serverTimezone=UTC
jdbc.username=root
jdbc.password=*******
说明:

纯注解并没有比半注解省事,所以在自己选择时优选半注解;

2、 数据源匹配

图示:

、spring整合junit问题分析和解决

问题分析:

应用程序的入口:

main方法;

junit单元测试中,没有main方法也能执行:

因为junit继承了一个main方法,这个main方法会判断当前测试类中有@Test注解的方法,并使其执行;

junit不管我们是否使用了spring框架:

不会读取配置文件/配置类来创建spring容器;

结论:

当测试放大执行时,没有Ioc容器,就算写了Autowired注解,也无法实现注入;

问题解决:

导入坐标:

代码语言:javascript代码运行次数:0运行复制
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

修改AccountServiceTest代码:

代码语言:javascript代码运行次数:0运行复制
package com.;

import com..SpringConfiguration;
import com.zibo.domain.Account;
import com.zibo.service.IAccountService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.ApplicationContext;
import org.annotation.AnnotationConfigApplicationContext;
import org.support.ClassPathXmlApplicationContext;
import org.ContextConfiguration;
import org.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * 使用junit单元测试进行测试
 * spring整合junit配置:
 *  1、导入spring整合junit的jar(坐标);
 *  2、使用junit提供的注解,把原有的main方法替换成spring提供的@Runwith;
 *  、告知spring的运行器,spring的ioc创建是基于xml还是注解,并说明其位置,使用@ContextConfiguration;
 *  ContextConfiguration:
 *      locati:指定xml文件的位置,加上classpath关键字,表示在类路径下;
 *      classes:指定注解类所在的位置;
 *  备注:当我们使用5.x版本的时候,junit的jar必须是4.12以上;
 */
@RunWith()
@ContextConfiguration(classes = )
public class AccountServiceTest {
//    private ApplicationContext ac;
    @Autowired
    private IAccountService as;
    @Before
    public void init(){
        //1、获取容器
//        ac = new ClassPathXmlApplicationContext("bean.xml");
//        ac = new AnnotationConfigApplicationContext();
        //2、得到业务层对象
//        as = ac.getBean("accountService", );
    }
    @Before
    public void end(){
//        ();
    }
    @Test
    public void testFindAllAccount(){
        //、执行方法
        List<Account> accounts = as.findAllAccount();
        //4、遍历输出
        for (Account account : accounts) {
            println(account);
        }
    }
    @Test
    public void testFindAccountById(){
        Account account = as.findAccountById(1);
        println(account);
    }
    @Test
    public void testSave(){
        Account account = new Account();
        account.setame("大哥");
        account.setMoney(2000);
        as.saveAccount(account);
    }
    @Test
    public void testUpdate(){
        Account account = new Account();
        account.setId();
        account.setame("二哥");
        account.setMoney(000);
        as.updateAccount(account);
    }
    @Test
    public void testDelete(){
        as.deleteAccountById(1);
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2025-01-06,如有侵权请联系 cloudcommunity@tencent 删除spring配置学习笔记优化注解

#感谢您对电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格的认可,转载请说明来源于"电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格

本文地址:http://www.dnpztj.cn/biancheng/1199194.html

相关标签:无
上传时间: 2025-07-23 14:34:10
留言与评论(共有 15 条评论)
本站网友 黄山毛豆腐
19分钟前 发表
原始发表:2025-01-06
本站网友 迅雷最新
14分钟前 发表
默认值为当前方法的名称; * 细节:当我们使用注解配置方法时
本站网友 滨江凯旋门
7分钟前 发表
* 作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器; * 属性:name用于指定bean的id
本站网友 小额贷款网
29分钟前 发表
spring框架去容器中查有没有可用的bean对象; * 查的方式和Autowired注解的作用是一致的; */ @Configuration @ComponentScan(basePackages = "com.zibo")//可省略为@ComponentScan("com.zibo") public class SpringConfiguration { //用于创建QueryRunner对象 @Bean(name = "runner") @Scope("prototype") public QueryRunner createQueryRunner(DataSource dataSource){ return new QueryRunner(dataSource); } //用于创建数据源对象 @Bean(name = "dataSource") public DataSource createDataSource(){ try { ComboPooledDataSource ds = new ComboPooledDataSource(); ds.setDriverClass("jdbc.Driver"); ds.setJdbcUrl("jdbc
本站网友 百度码
11分钟前 发表
* 作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器; * 属性:name用于指定bean的id
本站网友 宝宝晚上哭闹怎么办
5分钟前 发表
应该写在配置文件中;优化后的代码:SpringConfiguration配置类:代码语言:javascript代码运行次数:0运行复制package com.; import ComboPooledDataSource; import org.apachem.dbutils.QueryRunner; import org.annotation.*; import javax.sql.DataSource; import java.beans.PropertyVetoException; /** * 该类是一个配置类
本站网友 院感网
15分钟前 发表
得到业务层对象 as = ac.getBean("accountService"
本站网友 与日月同辉
16分钟前 发表
当不写时
本站网友 经济适用房购买条件
19分钟前 发表
都是指定spring在创建容器时要扫描的包; * 备注:我们使用此注解就等同于在xml中配置:<context
本站网友 裸睡
5分钟前 发表
); } @Before public void end(){ // (); } @Test public void testFindAllAccount(){ //
本站网友 基金赎回几天到账
12分钟前 发表
应该写在配置文件中;优化后的代码:SpringConfiguration配置类:代码语言:javascript代码运行次数:0运行复制package com.; import ComboPooledDataSource; import org.apachem.dbutils.QueryRunner; import org.annotation.*; import javax.sql.DataSource; import java.beans.PropertyVetoException; /** * 该类是一个配置类
本站网友 养殖业羊
24分钟前 发表
默认是单例
本站网友 防过敏
25分钟前 发表
问题发现和解决1
本站网友 光大证券下载
27分钟前 发表
spring整合junit问题分析和解决问题分析:应用程序的入口:main方法;junit单元测试中