Spring_02

基于注解的 IOC 配置

  1. 告知spring使用注解配置
bean.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">

    <!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在bean的约束中,
            而是一个名称为context名称空间和约束-->
    <context:component-scan base-package="com.itheima"></context:component-scan>

</beans>
  1. 用于创建对象的注解:@Component
 * 用于创建对象的注解:
 *      作用就和在xml配置文件中编写一个<bean>标签实现的功能是一样的
 *      @Component:
 *          作用:用于把当前类对象存入spring标签中
 *          属性:value用于指定bean的id,当我们不写时,默认是当前类名且首字母改小写
 *      @Controller:表现层
 *      @Service:业务层
 *      @Repository:持久层
 *      以上三个注解的作用和属性与Component是一模一样,
 *      他们三个是spring框架为我们提供的明确的三层使用的注解,使我们的三层对象更加清晰
/**
 * 曾经xml的配置:
 *     <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
 *     scope="" init-method="" destroy-method="">
 *          <property name="" value="" ref=""></property>
 *     </bean>
 */
//@Component(value = "accountService")
@Service(value = "accountService")
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao = new AccountDaoImpl();

    public AccountServiceImpl(){
        System.out.println("对象创建了");
    }

    public void saveAccount() {
        accountDao.savaAccount();
    }
}
  1. 用于注入数据的注解:
 * 作用和在xml配置文件中的bean标签中写一个<property>标签的作用是一样的
 *      Autowired:
 *          作用:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
 *               如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错
 *               如果iod容器中有多个类型匹配时,
 *          出现位置:
 *              可以是变量上,也可以是方法上
 *          细节:在使用注解注入时,set方法就不是必须的了
 *
 *      Qualifier:
 *          作用:在按照类型注入的基础上,再按照名称注入。它在给类成员注入时不能单独使用,但是在给方法参数注入时可以
 *          属性:value:用于指定注入bean的id
 *
 *      Resource:
 *          作用:直接按照bean的id注入,它可以独立使用
 *          属性:name:用于指定bean的id
 *
 *      以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现
 *      另外,集合类型的注入只能通过xml来实现
 *
 *      @Value:
 *          作用:用于注入基本类型和String类型的数据
 *          属性:value:用于指定数据的值,它可以spring中的SpEL(也就是spring的el表达式)
 *              SpEL的写法:${表达式}
  • 创建dao对象时使用@Autowired自动注入,如果存在多个daoImpl,那么spring会按照变量名accountDao来匹配对应的Dao实现类,如果找不到对应的impl会报错,我么可以使用@Qualifier来配置要注入的daoImpl的Repository的value。
    由于在类成员的注释中Autowired和Qualifier要成对出现,我们也可以使用另一个注解Resource代替。
@Service(value = "accountService")
//@Scope("prototype") 配置bean作用范围
public class AccountServiceImpl implements IAccountService {
    //ioc有多个注入匹配
//    @Autowired
//    @Qualifier("accountDao2")
    @Resource(name = "accountDao1")
    private IAccountDao accountDao2 = null;
	//虽然命名为dao2,但是根据注解来找,实现的是dao1的实现类
    public void saveAccount() {
        accountDao2.savaAccount(); //保存了账户111111
    }
}
  1. 其他注解
 * 用于改变作用范围的:
 *      作用和在bean标签中使用scope属性实现的功能是一样的
 *      Scope:
 *          作用:用于指定bean的作用范围
 *          属性:value指定范围的取值。常用取值:singleton prototype
 *
 * 生命周期相关:了解
 *      作用和在bean标签中使用init-method和destroy-method的作用是一样的
 *      PreDestroy:
 *          作用:用于指定销毁方法
 *      PostConstruct:
 *          作用:用于指定初始化方法
@Service(value = "accountService")
//@Scope("prototype") 配置bean作用范围
public class AccountServiceImpl implements IAccountService {
    @Resource(name = "accountDao1")
    private IAccountDao accountDao1 = null;

    public void saveAccount() {
        accountDao1.savaAccount();
    }

    @PostConstruct
    public void init() {
        System.out.println("初始化.....");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("销毁.....");
    }
}

基于xml的IOC案例

  1. 创建java项目,编写domain实体类,dao和service层的代码,Service要提供dao的注入,dao要提供QueryRunner的注入,使用set方式注入。
public class AccountDaoImpl implements IAccountDao {
    private QueryRunner runner;
    //也可以由spring提供
    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }
	......增删改查
	编写具体的sql逻辑
}
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;
    //提供注入
    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }
	......调用dao的增删改查方法
}
  1. 配置bean.xml
    在QueryRunner中继续注入数据源,需要配置数据源对象,并在数据源对象中注入连接数据库需要的信息。
<?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">

    <!--配置Service-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <!--注入dao对象-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <!--配置dao对象-->
    <bean id="accountDao" class="com.itheima.Dao.impl.AccountDaoImpl">
        <!--注入QueryRunner对象-->
        <property name="runner" ref="runner"></property>
    </bean>
    <!--配置QueryRunner对象-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>
    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/eesy?characterEncoding=utf8"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
</beans>
  1. 测试
public class AccountServiceTest {
    @Test
    public void testFindAll() {
        //1 获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2 得到业务层对象
        IAccountService as = (IAccountService) ac.getBean("accountService");
        //3 执行方法
        List<Account> accounts = as.finaAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
    ......其他测试类似
}

使用注解Ioc改造项目

更改xml头声明格式:
因为使用注解配置,所以我们自己写的实现类的xml可以删掉了,包括实现类中因注入提供的set方法也可以删除。

<?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">

    <!--告知spring在创建容器时要扫描的包-->
    <context:component-scan base-package="com.itheima"></context:component-scan>
    <!--配置QueryRunner对象-->
  	 ...
    <!--配置数据源-->
   	 ...
</beans>

使用注解配置:

@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    //注解注入 -- 唯一,不需指定Qualifier
    @Autowired
    private IAccountDao accountDao;
	...
}
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;
    ...
}

Spring的新注解

  1. 改造上面案例,不使用xml配置文件,完全使用注解来配置。
    创建一个新的配置类代替bean.xml
/**
 * Spring中的新注解
 * Configuration:
 *      作用:指定当前类是一个配置类
 *      细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写
 *           ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
 *
 * ComponentScan:
 *      作用:用于通过注解指定spring在创建容器时使用的包
 *      属性:
 *          value == basePackages作用相同,都是用于指定创建容器时要扫描的包
 *              我们使用此注解就相当于在xml中配置了:
 *              <context:component-scan base-package="com.itheima"></context:component-scan>
 *  Bean:
 *      作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
 *      属性:
 *          name:用于指定bean的id,不写时默认值是当前方法的名称
 *      细节:当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象
 *           查找的方式和Autowired的作用是一样的,
 */
// 该类是一个配置类,它的作用和bean.xml是一样的
@Configuration
@ComponentScan(basePackages = "com.itheima")
public class SpringConfiguration {
    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource(){
        ComboPooledDataSource ds = new ComboPooledDataSource();
        try {
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy?characterEncoding=utf8");
            ds.setUser("root");
            ds.setPassword("root");
            return ds;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }
}
//使用注解方式的获取容器
public class AccountServiceTest {
    @Test
    public void testFindAll() {
        //1 获取容器
//        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        //作为AnnotationConfigApplicationContext对象创建的参数时
        //SpringConfiguration可以不用注解Configuration标识
        ...
}
  1. Configuration注解
    作为AnnotationConfigApplicationContext对象创建的参数时,配置类的注解@Configuration可以省略,但是不是所有情况都可以省略,当有多个配置类的时候。
  • 第一种:在配置类中加入要扫描的存放配置的包,并将用到的配置类用@Configuration标识。
//SpringConfiguration.java
@Configuration
@ComponentScan(basePackages = {"com.itheima","config"})  //增加扫描包config
public class SpringConfiguration {

}

//JdbcConfig.java
/**
 * 和spring连接数据库相关的配置类
 */
@Configuration
public class JdbcConfig {
    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     */
   ...

    /**
     * 创建数据源对象
     */
   ...
}

测试类代码不做修改
  • 第二种:省略Configuration注解,将其他需要的配置类一起作为AnnotationConfigApplicationContext对象创建的参数传入。
    这个时候也不需要在SpringConfiguration 中配置config扫描包了,因为不管配不配,都会去扫描JdbcConfig。
    但是这种配置方法使得SpringConfiguration 和JdbcConfig是并列关系,而我们想实现的功能:SpringConfiguration是一个大配置类,而里面包含若干个小配置类JdbcConfig。
@Test
public void testFindAll() {
     //1 获取容器
     ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class, JdbcConfig.class);
    ......
 }
  • 第三种(@Import):既不注解配置类,不配置扫描包,也不作为参数传入。
/*
 *	Import:
 *      作用:用于导入其他配置类
 *      属性:value用于指定其他配置类的字节码
 *          当我们使用Import的注解之后,有Import注解的类就是父配置类,而导入的都是子配置类
 */
//@Configuration
@ComponentScan(basePackages = "com.itheima")
@Import(JdbcConfig.class)
public class SpringConfiguration {

}
  1. 使用properties配置文件
 *  @ PropertySource:
 *      作用:用于指定properties文件的位置
 *      属性:
 *          value:指定文件的名称和路径
 *          关键字:classpath:表示类路径下
//@Configuration
@ComponentScan(basePackages = "com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")   //classpath表示后面的路径是类路径
public class SpringConfiguration {

}
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;
    ...JDBC中的配置使用properties文件,不要写死。
}
  1. @Qualifier注解的另一种使用(在方法参数上)
public class JdbcConfig {
   ...
    /**
     * 用于创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(@Qualifier("ds1") DataSource dataSource){
        //注入时先按照形参匹配dataSource,如果没有类型匹配或者有多个符合时,就需要Qualifier指定对应的引用
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource(){
       ...
    }

    @Bean(name = "ds1")
    public DataSource createDataSource1(){
       ...
    }
}
  1. Spring整合Junit的配置
    因为juint的运行器不能在测试方法中通过注解的方法读取外部文件。
    如果这两者整合后,就可以替换junit的运行器为SpringJUnit4ClassRunner,测试方法就可以通过注解读取外部文件。
在pom.xml中导入一个依赖
	<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>

 * Spring整合Junit的配置
 *      1. 导入Spring整合的junit的jar(坐标)
 *      2. 使用Junit提供的一个注解把原有的main方法替换了,替换成spring提供的
 *      @Runwith
 *      3. 告知spring的运行期,spring和ioc的创建是基于xml的还是注解的,并且说明位置
 *      @ContextConfiguration
 *          locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
 *          classes:指定注解类所在的位置
 *
 *     当我们使用spring 5.x版本的时候,要求junit的jar必须是4.12及以上
//使用xml文件配置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private IAccountService as;	//必须配置,否则会注入失败

    @Test
    public void testFindAll() {
       /* //1 获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2 得到业务层对象
        IAccountService as = (IAccountService) ac.getBean("accountService");*/
        //3 执行方法
        List<Account> accounts = as.finaAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
}
//使用注解配置
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    @Autowired
    IAccountService as;

    @Test
    public void testFindAll() {
        //3 执行方法
        List<Account> accounts = as.finaAllAccount();
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值