跳至主要內容

Spring的新注解

晨光-向大约 6 分钟JavaSpringJavaSpring

Spring的新注解

1. 新注解

注解作用取代bean.xml属性
@Configuration指定一个配置类
@ComponentScan用于通过注解指定spring在创建容器时要扫描的包<context:component-scan base-package="com.chggx"/>basePackages(value)
@Bean用于把当前方法的返回值作为bean对象存入spring的ioc容器中name(默认值: 当前方法名称)
@Import用于导入其他的配置类value: 1. 用于指定其他配置类的字节码 2. 当我们使用@Import的注解之后,有Import注解的类就是父配置类,而导入的都是子配置类
@PropertySource用于指定文件的名称和路径value: 指定文件的名称和路径 关键字: classpath,表示类路径下

2. 新注解取代xml

1. 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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--配置包扫描-->
    <!--告知spring在创建容器时要包扫描-->
    <context:component-scan base-package="com.chggx"/>

    <!--配置QueryRunner: 改为多例 property-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源-->
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>

    <!--配置数据源 C3p0数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--注入连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_jdbc"/>
        <property name="user" value="root"/>
        <property name="password" value="326868"/>
    </bean>

</beans>

2. 注解形式

  • 父配置类
/**
 * @Description: <h1> spring配置类,作用和bean.xml一样 </h1>
 * spring中的新注解:
 *      @Configuration:
 *          作用: 指定一个配置类
 *          细节:
 *              当配置类作为 new AnnotationConfigApplicationContext(SpringConfiguration.class) 对象创建的参数时,该注解可以不写,否则还是要写
 *      @ComponentScan:
 *          作用: 用于通过注解指定spring在创建容器时要扫描的包
 *                            同bean.xml中的
 *          属性:
 *               basePackages: 指定创建容器时要扫描的包
 *               value: 1). 它和 basePackages 的作用是一样的,都是用于指定创建容器时要扫描的包
 *                      2). 我们使用次注解就等同于在xml中配置了:
 *                                  <context:component-scan base-package="com.chggx"/>
 *      @Bean:
 *           作用: 用于把当前方法的返回值作为bean对象存入spring的ioc容器中
 *           属性:
 *               name: 用于指定bean的id. 当不写时.默认值就是当前方法名称
 *           细节:
 *               当我们使用注解方式时,如果方法有参数: spring框架会去容器中查找有没有可用的bean对象.
 *               查找的方式和@Autowired注解的作用是一样的
 *      @Import:
 *           作用: 用于导入其他的配置类
 *           属性:
 *              value: 1. 用于指定其他配置类的字节码
 *                     2. 当我们使用@Import的注解之后,有Import注解的类就是父配置类,而导入的都是子配置类,相当于new AnnotationConfigApplicationContext(SpringConfiguration.class);
 *      @PropertySource:
 *           作用: 用于指定文件的名称和路径
 *           属性:
 *              value: 指定文件的名称和路径
 *                      关键字: classpath,表示类路径下
 */
//@Configuration
@ComponentScan(basePackages = {"com.chggx","com.chggx.config"})
@Import(value = {JdbcConfig.class})
@PropertySource(value = "classpath:jdbcConfig.properties")
public class SpringConfiguration {


}

  • 数据原配置 (自配置类)
/**
 * @Description: <h1> 和spring连接数据库相关的配置类 </h1>
 */
//@Configuration
public class JdbcConfig {

    /**
     * @Value: 注入数据(基本类型和String类型)
     */
    @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 对象
     *  作用范围多例: prototype
     * @param dataSource 数据源
     * @return QueryRunner
     */
    @Bean(name = "runner")
    @Scope(value = "prototype")
    public QueryRunner createQueryRunner(DataSource dataSource) {
        return new QueryRunner(dataSource);
    }

    /**
     * 配置数据源
     * @return DataSource
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource() {
        try {
            // C3p0数据源
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass(driver);
            dataSource.setJdbcUrl(url);
            dataSource.setUser(username);
            dataSource.setPassword(password);
            return dataSource;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }

}
  • 数据源配置文件 jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_jdbc
jdbc.username=root
jdbc.password=326868

3. @Qualifier另一种使用

  1. 之前配合**@Autowired**来解决多类型注入问题.
  2. 现在在Spring中另一种使用
    • 解决与上边相似,如注入数据源是,数据源多个时,使用**@Qualifier**来确定
/**
 * 用于创建一个 QueryRunner 对象
 *  1. 作用范围多例: prototype
 *  2. 当有DataSource 是有多个数据源(多类型)时,此外用@Qualifier("dataSource1"): 来确定注入的类型(同@Autowired)
 * @param dataSource 数据源
 * @return QueryRunner
 */
@Bean(name = "runner")
@Scope(value = "prototype")
public QueryRunner createQueryRunner(@Qualifier("dataSource1") DataSource dataSource) {
    return new QueryRunner(dataSource);
}

/**
 * 配置数据源 1
 * @return DataSource
 */
@Bean(name = "dataSource1")
public DataSource createDataSource() {
    try {
        // C3p0数据源
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);
        return dataSource;
    } catch (PropertyVetoException e) {
        throw new RuntimeException(e);
    }
}

/**
 * 配置数据源 2
 * @return DataSource
 */
@Bean(name = "dataSource2")
public DataSource createDataSource2() {
    try {
        // C3p0数据源
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mybatisdb");
        dataSource.setUser(username);
        dataSource.setPassword(password);
        return dataSource;
    } catch (PropertyVetoException e) {
        throw new RuntimeException(e);
    }
}

4. junit

1. 普通junit

<!--junit 测试-->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
  • 问题
1、应用程序的入口
	main方法
2、junit单元测试中,没有main方法也能执行
	junit集成了一个main方法
	该方法就会判断当前测试类中哪些方法有 @Test注解
	junit就让有Test注解的方法执行
3、junit不会管我们是否采用spring框架
	在执行测试方法时,junit根本不知道我们是不是使用了spring框架
	所以也就不会为我们读取配置文件/配置类创建spring核心容器
4、由以上三点可知
	当测试方法执行时,没有Ioc容器,就算写了Autowired注解,也无法实现注入

2. Spring集成junit

  • 依赖
<!--spring test-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.6.RELEASE</version>
</dependency>
  • 配置
Spring整合junit的配置:
     1. 导入spring整合junit的jar包(即: 坐标)
     2. 使用Junit提供的一个注解把所有的main方法提花了,替换成spring提供的
         @RunWith: SpringJUnit4ClassRunner.class
     3. 告知spring的运行器,spring的ioc创建是基于xml还是注解的,并且说明位置
         @ContextConfiguration:
              locations(value): 指定xml文件的位置,加上classpath关键字,表示在类路径下
                 @ContextConfiguration(locations = "classpath:bean.xml")
              classes: 指定注解(配置)类所在的位置
                 @ContextConfiguration(classes = SpringConfiguration.class)

3. 案例 注解形式

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = "classpath:bean.xml")
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    /**
     * spring 整合 junit 方式: 可以使用 @Autowired 注入数据
     */
    @Autowired
    private AccountService accountService;

//    @Before
//    public void before() {
//        // =========== AnnotationConfigApplicationContext: 注解形式 ============
//        // 1. 获取容器
//        // 使用配置文件方式
////        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//        //  使用配置类方式 SpringConfiguration
//        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//        // 得到业务对象
//        accountService = ac.getBean("accountService", AccountService.class);
//    }

    @Test
    public void testFindAllAccount() {
        // 查询所有
        List<Account> accounts = accountService.findAllAccount();
        accounts.forEach(System.out::println);
    }
 }

5. @Lazy

Spring中的 @Lazy注解简析open in new window

Spring框架中@Lazy延迟加载原理和使用细节open in new window