Spring IOC纯注解开发

一、相关注解

spring中的新注解

  • Configuration

      作用:指定当前类是一个配置类
      细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。

  • ComponentScan

       作用:用于通过注解指定spring在创建容器时要扫描的包
       属性:
           value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。
                  我们使用此注解就等同于在xml中配置了:
                       <context:component-scan base-package="com.dgut"></context:component-scan>

  • Bean

       作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
       属性:
           name:用于指定bean的id。当不写时,默认值是当前方法的名称
       细节:
           当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象。
           查找的方式和Autowired注解的作用是一样的

  • Import

       作用:用于导入其他的配置类
       属性:
           value:用于指定其他配置类的字节码。
                   当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类

  • PropertySource

       作用:用于指定properties文件的位置
       属性:
           value:指定文件的名称和路径。
                   关键字:classpath,表示类路径下

二、改造

原本在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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
		
    <context:component-scan base-package="com.dgut"/>
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>
    <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/temperary"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>
</beans>

 下面建立两个配置类,它们的作用和上述xml的作用是一样的

  • SpringConfiguration类
@Configuration
@ComponentScan({"com.dgut"})
/**
 * PropertySource注解可以写在此处,也可以写在JdbcConfiguration处
 * @PropertySource("classpath:jdbcConfiguration.properties")
 */
/**
 * 引入数据库配置文件
 */
@Import(JdbcConfiguration.class)

/**
 * 可以SpringConfiguration中配置一些公共部分的配置
 */
public class SpringConfiguration {

}
  • JdbcConfiguration类
package config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;

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

/**
 * @author jcH
 * @create 2020-02-07 10:42
 */

@PropertySource("classpath:jdbcConfiguration.properties")
public class JdbcConfiguration {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.user}")
    private String user;
    @Value("${jdbc.password}")
    private String password;
    /**
     * 创建QueryRunner对象
     * @Qualifier("dataSource")作用:再多数据源的情况下指定需要注入的数据源
     * 此处为但数据源,没有必要加上这个注解,只是为了说明问题
     */
    @Bean("runner")
    public QueryRunner createQueryRunner(@Qualifier("dataSource") DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据库数据源
     */
    @Bean("dataSource")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass(driver);
            dataSource.setJdbcUrl(url);
            dataSource.setUser(user);
            dataSource.setPassword(password);
            return dataSource;
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        return null;
    }
}
  • jdbcConfiguration.properties配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/temperary
jdbc.user=root
jdbc.password=123456

至此,可以吧xml文件删掉

三、核心容器的加载

    @Test
    public void findAllTest(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        accountService = (IAccountService) ac.getBean("accountService");
        List<Account> accounts = accountService.findAll();
        accounts.forEach(System.out::println);
    }

 至此,已经完成纯注解开发。

发布了93 篇原创文章 · 获赞 80 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_40391011/article/details/104206958