spring(二)

spring(二)

基于注解的 IOC 配置

注解配置和 xml 配置要实现的功能都是一样 的,都是要降低程序间的耦合。只是配置的形式不一样。

一般情况下都是xml配置与注解结合使用

演示案例

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

表现层

/**
 * 模拟一个表现层,用于调用业务层
 */
public class Client {
    public static void main(String[] args) {
        //1,获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2,根据id获取Bean对象
        AccountService as = (AccountService) ac.getBean("accountService");
        AccountService as2 = (AccountService) ac.getBean("accountService");
        //AccountDao adao = (AccountDao) ac.getBean("accountDao");
        System.out.println(as==as2);
        //System.out.println(adao);
        //as.saveAccount();
    }
}

业务层实现类

@Component(value = "accountService")
//@Scope(value = "prototype")
public class AccountServiceImpl implements AccountService {
    /**
     * 自动按照类型注入数据
     */
/*  @Autowired
    @Qualifier(value = "accountDao1")*/
    @Resource(name = "accountDao2")
    private AccountDao accountDao = null;

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

账户的业务层实现类

曾经的XML的配置

<bean id="accountService" class = "x.xss.service.impl.AccountServiceImpl"

scope="" init-method = "" destroy-method = "">

<property name = "" value = ""/ref = ""></property>

</bean>
1,用于创建对象的注解

其的作用和在XML配置文件中编写一个标签实现的功能是一样的

(1)Component:

作用:用于把当前类对象存入spring容器中

属性

value:用于指定bean的id。当我们不写时,它的默认值是当前类名,且首字母改小写。

Controller:一般用在表现层

Service:一般用在业务层

Repository:一般用在持久层

以上三个注解他们的作用和属性与Component是一模一样。

spring框架为我们提供明确的三层使用的注解,使三层对象更加清晰

2,用于注入数据的注解

其的作用和在XML配置文件中编写一个标签实现的功能是一样的

(1)Autowired:

作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功.

如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错。

如果Ioc容器中有多个类型匹配时:先根据数据类型 找到那些匹配的,然后再根据变量名称,并将它作为 key,在核心容器中找到对应的value。这样并不方便。

出现位置

可以是变量上,也可以是方法上

细节:

在使用注解注入时,set方法就不是必须的了。

示例

有两个实现类 实现了一个接口

/**
 * 第一个实现类,都实现了AccountDao接口
 */
@Repository(value = "accountDao1")
public class AccountDaoImpl implements AccountDao {

    public void saveAccount() {
        System.out.println("保存了账户11111");
    }
}
/**
 * 第二个实现类,也实现了AccountDao接口
 */
@Repository(value = "accountDao2")
public class AccountDaoImpl2 implements AccountDao {
    public void saveAccount() {
        System.out.println("保存了账户22222222");
    }
}
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao = null;
    public void saveAccount(){
        accountDao.saveAccount();
    }
}

在这里插入图片描述

(2)Qualifier:

作用:在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用。

但是在给方法参数注入时可以 但是必须要与Autowired 一起用

属性:

value:用于指定注入bean的id。

    @Autowired
    @Qualifier(value = "accountDao2")
    private AccountDao accountDao = null;

(3)Resource

作用:直接按照bean的id注入。它可以独立使用

属性:

name:用于指定bean的id。

@Resource(name = "accountDao2")
private AccountDao accountDao = null;

以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现。

另外,集合类型的注入只能通过XML来实现。

(4)Value

作用:用于注入基本类型和String类型的数据

属性

value:用于指定数据的值。它可以使用spring中SpEL(也就是spring的el表达式)

​ SpEL的写法:${表达式}

3,用于改变作用的注解

其的作用就和在bean标签中使用scope属性实现的功能是一样的

(1)Scope

作用:用于指定bean的作用范围属性:

value:指定范围的取值。常用取值:单例singleton 多例prototype 不写,默认单例
*==================================================================================================

4,和生命周期有关的注解(了解)

他的作用就和在bean标签中使用init-method和destroy-method的作用是一样的

(1)PreDestroy

作用:用于指定销毁方法

(2)PostConstruct

作用:用于指定初始化方法

使用 spring 的 IoC 的实现账户的 CRUD

1,使用XML配置的IOC配置

持久层实现类代码

/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements AccountDao {
    private QueryRunner runner;
    //set方法
    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }


	//查询所有
    public List<Account> findAll() {
        try {
            return runner.query("select * from account",
                                new BeanListHandler<Account>(Account.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
	//根据id查找
    public Account findAccountById(Integer id) {
        try {
            return runner.query("select * from account where id=?",
                                new BeanHandler<Account>(Account.class),id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
	//保存
    public void saveAccount(Account account) {
        try {
            runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

业务层实现类

/**
 * 业务层实现类
 */
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
    //set方法
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    
    
    public List<Account> findAll() {
        return accountDao.findAll();
    }
    public Account findAccountById(Integer id) {
        return accountDao.findAccountById(id);
    }
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

配置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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--配置Service-->
    <bean id="accountService" class="x.xss.service.impl.AccountServiceImpl">
        <!--注入dao-->
        <property name="accountDao" ref="accountDao"></property>
    </bean>
<!--配置dao-->
    <bean id="accountDao" class="x.xss.dao.impl.AccountDaoImpl">
        <!--注入QueryRunner 方法一 set方法 -->
        <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/day724"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
</beans>

测试类

/**
 * 测试类
 */
public class AccountServiceTest {
    private ApplicationContext ac;
    private AccountService accountService;
    @Before
    public  void init() {
        //1,获取核心容器对象
        ac = new ClassPathXmlApplicationContext("bean.xml");
        //2,根据id获取Bean对象
     accountService = (AccountService)ac.getBean("accountService",AccountService.class);
    }
    //查询所有
    @Test
    public void testFindAll(){
        List<Account> accounts = accountService.findAll();
        for(Account account:accounts){
            System.out.println(account);
        }
    }
    //查询一个
    @Test
    public void testFindOne(){
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }
    //保存
    @Test
    public void testSave(){
        Account account = new Account();
        account.setName("电脑");
        account.setMoney(5000f);
        accountService.saveAccount(account);
    }
}

2,基于 XML 和 注解 的 IOC 配置

持久层实现类代码

/**
 * 账户的持久层实现类
 */
@Repository(value = "accountDao")
public class AccountDaoImpl implements AccountDao {
    @Autowired
    private QueryRunner runner;

业务层实现类

/**
 * 业务层实现类
 */
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired

配置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在创建容器时要扫描的包-->
<context:component-scan base-package="x.xss"></context:component-scan>
<!--配置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/day724"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
</beans>

测试类

/**
 * 测试类
 */
public class AccountServiceTest {
    private ApplicationContext ac;
    private AccountService accountService;
    @Before
    public  void init() {
        //1,获取核心容器对象
        ac = new ClassPathXmlApplicationContext("bean.xml");
        //2,根据id获取Bean对象
     accountService = (AccountService)ac.getBean("accountService",AccountService.class);
    }
    //查询所有
    @Test
    public void testFindAll(){
        List<Account> accounts = accountService.findAll();
        for(Account account:accounts){
            System.out.println(account);
        }
    }
    //查询一个
    @Test
    public void testFindOne(){
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }
    //保存
    @Test
    public void testSave(){
        Account account = new Account();
        account.setName("电脑");
        account.setMoney(5000f);
        accountService.saveAccount(account);
    }
}

3,完全基于注解 的 IOC 配置

持久层实现类代码

/**
 * 账户的持久层实现类
 */
@Repository(value = "accountDao")
public class AccountDaoImpl implements AccountDao {
    @Autowired
    private QueryRunner runner;

业务层实现类

/**
 * 业务层实现类
 */
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

配置类

根目录下的config包下的SpringConfiguration类

1,spring中的新注解

(1)Configuration

作用:指定当前类是一个配置类

细节:当配置类作为ContextConfiguration(classes = SpringConfiguration.class)

(2)ComponentScan

作用:用于通过注解指定spring在创建容器时要扫描的包

属性:

value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。

使用了次注解等同于 :

–告知spring在创建容器时要扫描的包

<context:component-scan base-package=“x.xss”></context:component-scan>

(3)Bean

作用:注册Bean,用于把当前方法的返回值作为bean对象存入spring的ioc容器中

属性:

name:用于指定bean的id ,当不写时,默认是当前方法的名称。

细节:

当我们使用注解配置方法时,如果有参数,spring框架回去容器中查找

可用的bean对象,查找的方式与Autowired注解的作用是一样的。

(4)Import

作用:用于指定其它配置类的字节码。 .class

当我们使用Import的注解之后,有Import注解的类就是父配置类,而导入的都是子配置类

(5)PropertySource

作用:用于指定properties文件的位置

属性:

value:指定文件的名称和路径。

关键字:classpath,表示类路径下 + 地址 = 读取连接数据库的配置信息

/**
 * 配置类:它的作用与bean.xml一样
*/
@Configuration  //指定当前类是一个配置类
@ComponentScan(value = "x.xss")  //要扫描的包
@PropertySource("classpath:JdbcConfig.properties")//读取连接数据库的配置信息
public class SpringConfiguration {
    @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对象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")//用于把当前方法的返回值作为bean对象存入spring的ioc容器中
    @Scope(value = "prototype")
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }
    @Bean(name = "dataSource")//用于把当前方法的返回值作为bean对象存入spring的ioc容器中当不写时,默   认是当前方法的名称
    public DataSource createDataSource(){
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            dataSource.setDriverClass(driver);
            dataSource.setJdbcUrl(url);
            dataSource.setUser(username);
            dataSource.setPassword(password);
            return dataSource;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

测试类 同时整合Junit测试

为什么整合junit

1、应用程序的入口

main方法

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

junit集成了一个main方法

该方法就会判断当前测试类中哪些方法有 @Test注解

junit就让有Test注解的方法执行

3、junit不会管我们是否采用spring框架

在执行测试方法时,junit根本不知道我们是不是使用了spring框架

所以也就不会为我们读取配置文件/配置类创建spring核心容器4、由以上三点可知

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

使用Junit单元测试:

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 中

​ 配到XML中也可以使用。但是不采用配置到 xml 中! 原因:

第一:当我们在 xml 中配置了一个 bean,spring 加载配置文件创建容器时,就会创建对象。

第二:测试类只是在测试功能时使用,在项目中并不参与程序逻辑,要是在XML中创建了,并没有使用。那么存在容器中就会造成资源的浪费。

/*测试类,并整合了junit*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
    @Autowired
    private AccountService accountService = null;
	//查找所有
    @Test
    public void testFindAll(){
        List<Account> accounts = accountService.findAll();
        for(Account account:accounts){
            System.out.println(account);
        }
    }
    //查找一个
    @Test
    public void testFindOne(){
        Account account = accountService.findAccountById(1);
        System.out.println(account);
    }
	//保存
    @Test
    public void testSave(){
        Account account = new Account();
        account.setName("电话");
        account.setMoney(75000f);
        accountService.saveAccount(account);
    }
}

在这里插入图片描述

总结:一般使用XML与注解结合的方式,数据源等来自第三方,建议用XML

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值