使用注解首先要在配置文件中引入几行代码,在下面这个链接中搜索"xmlns:context"即可得到这段代码。将其复制到bean.xml配置文件中。链接
作用:告诉spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是在一个名称为context名称空间和约束中。
接着就可以写下面这个代码进行相关配置。
<context:component-scan base-package="com.itheima"></context:component-scan>
注解的类型与使用
* 用于创建对象的
* 它们的作用就和在XML配置文件中编写一个bean标签实现的功能一样
* Component:
* 用于把当前类对象存入spring容器中
* 属性:
* value:用于指定bean的id,当我们不写时默认值是当前类名且首字母该小写。
* Controller:一般用在表现层
* Service:一般用在业务层
* Repository:一般用在持久层
* 以上三个注解作用和属性与Component是一模一样的。
* 它们三个是spring框架为我们提供明确的三层使用的注释,使我们的三层对象更加清晰。
* 用于注入数据的
* 它们的作用就和在XML配置文件中bean标签中写一个property标签的作用是一样的
* Autowired:
* 作用:自动按照类型注入。只要容器中有唯一的bean对象类型和要注入的变量类型匹配,就可以注入成功。
* 如果IOC容器中没有任何bean的类型和要注入的变量类型匹配,则报错。
* 出现位置:可以是变量上,也可以是方法上
* 细节:
* 在使用注解注入时,set方法就不是必须的了。
* Qualifier:
* 作用:在按照类中注入的基础之上再按名称注入。它在给类成员注入时不能单独使用,但是在给方法参数注入时可以。
* 属性:
* value:用于指定要注入的id
* Resource:
* 作用:直接按照bean的id注入,可以独立使用
* 属性:
* name:用于指定bean的id
* 以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现
* 另外,集合类型的注入只能通过XML来实现
*
* value:
* 作用:用于注入基本类型和String类型的数据
* 属性:
* value:用于指定数据的值,它可以使用spring中的SpEL(也就是spring的el表达式)
* SpEL写法:${表达式}
* 用于改变作用范围的
* 它们的作用就和在bean标签中使用scope属性实现的功能是一样的
* Scope:
* 作用:用于指定bean的作用范围
* 属性:
* value:指定范围的取值。常用取值:singleton, prototype
* //@Scope("prototype")
* 和生命周期相关
* 它们的作用就和在bean标签中使用init-method和destroy-method的作用是一样的。
* PreDestroy
* 作用:用于指定销毁方法
* PostConstruct
* 作用:用于指定初始化方法
这个配置文件包括了之前学到的内容,有对象的创建(bean),注入数据(property和constructor-arg),ref等。
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="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"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
/**
* 账户持久层实现类
*/
public class AccountDaoImpl implements AccountDao {
private QueryRunner runner;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public List<Account> findAllAccount() {
try {
return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(Integer accountId) {
try {
return runner.query("select * from account where id = ?", new BeanHandler<Account>(Account.class), accountId);
} 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 void updateAccount(Account account) {
try {
runner.update("update account set name =?, money=? where id=?", account.getName(), account.getMoney(), account.getId());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void deleteAccount(Integer accountId) {
try {
runner.update("delete from account where id=?", accountId);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
最高通过见一个测试类来检验构造是否正确。
package com.itheima.test;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* 使用Junit单元测试:测试我们的配置
*/
public class AccountServiceTest {
@Test
public void testFindAll() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
AccountService as = ac.getBean("accountService", AccountService.class);
//3.执行方法
List<Account> accounts = as.findAllAccount();
for(Account account : accounts){
System.out.println(account);
}
}
@Test
public void testFindOne() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
AccountService as = ac.getBean("accountService", AccountService.class);
//3.执行方法
Account account = as.findAccountById(2);
System.out.println(account);
}
@Test
public void testSave() {
Account account = new Account();
account.setName("test");
account.setMoney(12345f);
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
AccountService as = ac.getBean("accountService", AccountService.class);
//3.执行方法
as.saveAccount(account);
}
@Test
public void testUpdate() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
AccountService as = ac.getBean("accountService", AccountService.class);
//3.执行方法
Account account = as.findAccountById(4);
account.setMoney(23456f);
as.updateAccount(account);
}
@Test
public void testDelete() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
AccountService as = ac.getBean("accountService", AccountService.class);
//3.执行方法
}
}
之前用的是基于xml的方式进行实现,这里基于注解首先要引入spring约束。上面网址中可以查找。
接着告诉spring在创建容器时需要扫描的包。
<context:component-scan base-package="com.itheima"></context:component-scan>
基于注解对基于xml的代码进行改造包括:
最后构建测试类进行测试:
@test
package test;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* 使用Junit单元测试:测试我们的配置
*/
public class AccountServiceTest {
@Test
public void testFindAll() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
AccountService as = ac.getBean("accountService", AccountService.class);
//3.执行方法
List<Account> accounts = as.findAllAccount();
for(Account account : accounts){
System.out.println(account);
}
}
@Test
public void testFindOne() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
AccountService as = ac.getBean("accountService", AccountService.class);
//3.执行方法
Account account = as.findAccountById(2);
System.out.println(account);
}
@Test
public void testSave() {
Account account = new Account();
account.setName("test");
account.setMoney(12345f);
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
AccountService as = ac.getBean("accountService", AccountService.class);
//3.执行方法
as.saveAccount(account);
}
@Test
public void testUpdate() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
AccountService as = ac.getBean("accountService", AccountService.class);
//3.执行方法
Account account = as.findAccountById(4);
account.setMoney(23456f);
as.updateAccount(account);
}
@Test
public void testDelete() {
//1.获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.得到业务层对象
AccountService as = ac.getBean("accountService", AccountService.class);
//3.执行方法
}
}
bean.xml的依赖可以通过新建一个配置类进行替代。
@configuration
作用是指定当前类是一个配置类。
细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。
比如:
//1.获取容器
// ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
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相同。
@Configuration
@ComponentScan("com.itheima")
public class SpringConfiguration {
/**
* 用于创建一个QueryRunner对象
* @param dataSource
* @return
*/
@Bean(name="runner")
@Scope("prototyoe")
public QueryRunner createQueryRunner(DataSource dataSource) {
return new QueryRunner(dataSource);
}
/**
* 创建数据源对象
* @return
*/
@Bean(name="dataSource")
public DataSource createDataSource() {
try{
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy");
ds.setUser("root");
ds.setPassword("root");
return ds;
} catch(Exception e) {
throw new RuntimeException();
}
}
}
其他的注解,还有:
@Import
作用:用于导入其他的配置类。
属性:value:用于指定其他配置类的字节码。当我们使用Import的注解之后,有Import注解的类就是父配置类,而导入的类是子配置类。
@PropertySource
作用:用于指定properties文件的位置
关键字:classpath,表示类路径下。
解决方法时在换掉不能加载容器的main方法,换成可以加载的。
具体步骤:
@ContextConfiguration(classes=SpringConfiguration.class)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>