Spring学习(二)

Spring基于注解的IOC

SpringIOC的常用基本注解

1、用于创建对象的:作用与在xml文件中< bean >标签一样
Component:
作用:把当前类对象放入Spring容器中
value标签:用于指定bean的id,如果不写,则默认为当前的类名且首字母小写
Controller:一般用在表现层
Service:一般用在业务层
Repository:一般用在持久层
以上三个是spring框架为我们提供明确的三层使用的注解使我们三层对象更加清 晰,其作用与Component相同,都是把类对象放入IOC容器中。

2、用于注入数据的:作用与在xml文件中< bean>标签里的< property >标签一样
Autowired:
作用:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就能注入成功
如果IOC容器没有任何bean类型和要注入的变量类型匹配,则报错,如果IOC有多个匹配时,
根据变量名称寻找与bean的id对应的bean注入
出现位置:可以是变量上,也可以是方法上
注意:在使用注解注入时,set方法不是必须的

Qualifier:
作用:在按照类中注入的基础之上再按照名称注入,在给类成员注入时不能单独注入,但在给方法参数注入时可以,必须配合Autowired使用
属性:value:用于指定注入bean的id

Resource:
作用:直接按照bean的id注入,可以独立使用
属性:
name:用于指定bean的id
以上三个注解只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解注入,
另外,集合类型的注入只能通过xml实现

Value:
作用:用于注入基本类型和String类型的数据
属性:
value:用于指定数据的值,它可以使用spring中SpEL(spring的el表达式)
SpEL的写法:${表达式}

3、用于改变作用范围的:作用与< bean>标签中的< scope>标签一样
Scope:
作用:用于指定bean的作用范围(使创建的对象为多例或单例)
属性:
value:指定范围的取值。常用取值:singleton,prototype

4、与生命周期相关的(了解即可):作用和< bean>标签中的< init-method>< destroy-method>一样
PreDestroy:用于指定销毁方法
PostConstruct:指定初始化方法

测试:
1、首先我们需要通过xml文件获取bean对象(xml文件可以完全去掉,下面会有讲解),通过<context:component-scan base-package=“包名”></context:component-scan>
扫描相应的包,这样spring容器中就有了注解的类对象。

<?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在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,
       而是一个名称为context名称空间和约束中  -->
    <context:component-scan base-package="com.itheima"></context:component-scan>
</beans>

2、编写代码并进行测试

@Repository("accountDao1")
public class AccountDaoImpl implements IAccountDao {
    public void saveAccount() {

        System.out.println("保存了账户");
    }
}
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
@Resource(name = "accountDao1")
    private IAccountDao accountDao=null;

    public void saveAccount() {
        System.out.println("service中的saveAccount方法执行了");
        accountDao.saveAccount();
    }
}
public class Test {
    public static void main(String[] args) {
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        IAccountService as=(IAccountService) ac.getBean("accountService");
        as.saveAccount();
    }
}

在这里插入图片描述
测试完成

配置注解

一个配置类,作用与bean.xml一样
新注解
1、Configuration
作用:指定当前类是一个配置类
注意:当配置类作为AnnotationConfigurationContext对象创建的参数时,该注解可以不写

2、ComponentScan
作用:通过注解指定spring在创建容器时要扫描的包
属性:
value:和basePackages一样,用于指定创建容器要扫描的包
使用此注解等同于在xml中配置了:
<context:component-scan base-package=“com.itheima”></context:component-scan>,所以xml文件也就能完全去掉了

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

4、Import:
作用:用于导入其他配置类
属性:
value:用于指定其他配置类的字节码
当使用Import之后,有Import的类就是主配置类,导入的就是子配置类

当存在多个配置类的时候,就需要将配置类进行声明,方法有三:
1:除了作为AnnotationConfigurationContext对象创建的参数的类,其他类都加上@Configuration注解
2:把所有的配置类都作为AnnotationConfigurationContext对象创建的参数
3:用@Import注解将配置类导入一个配置类作为该配置类的子配置类

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

这里引入PropertySource注解主要是出于为了提高程序的可维护性,举个例子:

public class JdbcConfig {
    /*
     *用于创建QueryRunner对象
     * */
    @Bean(name = "runner")
    @Scope("prototype")/*使创建的容器对象为多例*/
    public QueryRunner createQueryRunner(DataSource dataSource)
    {
        return new QueryRunner(dataSource);
    }
 @Bean(name = "dataSource")
    public DataSource createDataSource()
    {
        ComboPooledDataSource ds=new ComboPooledDataSource();
        try {
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/account");
            ds.setUser("root");
            ds.setPassword("root");
            return ds;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }

    }
}

这里的代码用的Import注解来配置多个配置类,所以我们在主配置类用PropertySource注解即可

@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {

}

在这段配置类的代码中所有的配置信息都是直接写死的,而我们希望的是它是可变的,PropertySource注解的作用就在于此。
首先创建一个properties文件,并进行简单的编写:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/account
jdbc.user=root
jdbc.password=root

配置类的内容进行修改:

public class JdbcConfig {
    /*
     *用于创建QueryRunner对象
     * */
    @Bean(name = "runner")
    @Scope("prototype")/*使创建的容器对象为多例*/
    public QueryRunner createQueryRunner(DataSource dataSource)
    {
        return new QueryRunner(dataSource);
    }

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.user}")
    private String user;

    @Value("${jdbc.password}")
    private String password;

    @Bean(name = "dataSource")
    public DataSource createDataSource()
    {
        ComboPooledDataSource ds=new ComboPooledDataSource();
        try {
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(user);
            ds.setPassword(password);
            return ds;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }

    }
}

这样写好像增加了我们要写的代码数量,但是对于相关的参数,它变得更灵活了,而且由于properties文件的内容较为简单,对于相关参数的修改也更为方便,有利于程序的维护

测试:

子配置类

public class JdbcConfig {
    /*
     *用于创建QueryRunner对象
     * */
    @Bean(name = "runner")
    @Scope("prototype")/*使创建的容器对象为多例*/
    public QueryRunner createQueryRunner(DataSource dataSource)
    {
        return new QueryRunner(dataSource);
    }

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.user}")
    private String user;

    @Value("${jdbc.password}")
    private String password;

    @Bean(name = "dataSource")
    public DataSource createDataSource()
    {
        ComboPooledDataSource ds=new ComboPooledDataSource();
        try {
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(user);
            ds.setPassword(password);
            return ds;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }

    }
}

编写主配置类:

@ComponentScan(basePackages = "com.itheima")
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {

}

编写持久层接口及其实现类:

public interface IAccountDao {
    List<Account> findAllAccount();

    Account findAccountById(Integer id);

    void saveAccount(Account account);

    void updateAccount(Account account);

    void deleteAccount(Integer id);
}
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private QueryRunner runner;

    public List<Account> findAllAccount() {
        try {
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountById(Integer id) {
        try {
            return runner.query("select *from account where id=?",new BeanHandler<Account>(Account.class),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {
        try {
            runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateAccount(Account account) {
        try {
            runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void deleteAccount(Integer id) {
        try {
            runner.update("delete from account where id=?",id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

编写service层接口及其实现类:

public interface IAccountService {

    List<Account> findAllAccount();

    Account findAccountById(Integer id);

    void saveAccount(Account account);

    void updateAccount(Account account);

    void deleteAccount(Integer id);
}
@Service("accountService")
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findAccountById(Integer id) {
        return accountDao.findAccountById(id);
    }

    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    public void deleteAccount(Integer id) {
        accountDao.deleteAccount(id);
    }
}

编写测试程序:
这里只测试其中一个功能

@Test
    public void testFindAll() {
        ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfiguration.class);
        IAccountService as=ac.getBean("accountService",IAccountService.class);
        List<Account> accounts=as.findAllAccount();
        for (Account account:accounts)
        {
            System.out.println(account);
        }
    }

测试结果:
在这里插入图片描述

Spring整合Junit遇到的问题及解决

在使用Spring整合Junit进行测试时,会碰到这样一个问题:
所有的测试方法都要有这样两行代码:

ApplicationContext ac=new AnnotationConfigApplicationContext(SpringConfiguration.class);
IAccountService as=ac.getBean("accountService",IAccountService.class);

为了减少代码的数量,我们直接把要获取的IAccountService类的对象直接放在所有测试方法外作为测试方法的一个属性:

@Autowired
    private IAccountService as;

但是运行之后问题仍然没有解决:当我们运行如下代码时,as对象是空的,因为当我们运行某个测试方法时,Junit只会执行方法内的代码,对于我们在整个程序中是否有使用Spring框架并不会进行判断,所以也不会读取IOC容器,即使写了@Autowired注解也无法实现注入。

@Test
    public void testFindAll() {
        List<Account> accounts=as.findAllAccount();
        for (Account account:accounts)
        {
            System.out.println(account);
        }
    }

解决:
1、导入spring整合Junit的jar包(坐标),导入Spring-test jar包
2、使用Junit的一个注解把原有的main方法替换了,替换成spring提供的(使用@RunnerWith),即将Junit的Runner用Spring提供的SpringJUnit4ClassRunner替换,由于它是由Spring提供的,所以它会创建容器读取配置文件。
3、告知spring的运行器,spring的IOC的创建是基于xml还是注解的,并且说明位置
@ContextConfiguration
Locations:指定xml文件的位置,加上classpath关键字,表示在类路径下
classes:指定注解类所在的位置

所以我们只需在测试类前加上这两行注解即可:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes =SpringConfiguration.class )
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值