Spring中的常用注解
想使用注解配置,必须先在spring配置文件中添加一下约束
还有告诉spring创建容器时要扫描的包,配置的标签不是在beans的约束,而是一个名称为
context名称空间中和约束中
<?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名称空间中和约束中-->
<!-- 要扫描的包是com.itheima和其所有子包-->
<context:component-scan base-package="com.itheima"></context:component-scan>
</beans>
创建对象的注解
* 创建对象的注解
* 他们的作用就和在xml配置文件中编写一个<bean>标签实现的功能一样
@Component
* @Component:
* 作用:用于把当前类对象存入spring容器中
* 属性:
* value:用于指定bean的id,当不写value属性的值时,它默认值为是当前类名,且首字母小写
package com.itheima.service.impl;
import com.itheima.dao.IAccountDao;
import com.itheima.dao.impl.AccountDaoImpl;
import com.itheima.service.IAccountService;
import org.springframework.stereotype.Component;
/**
* 账户业务层实现类
*/
@Component(value = "accountService")
public class AccountServiceImpl implements IAccountService {
public AccountServiceImpl(){
System.out.println("AccountServiceImpl被创建...");
}
private IAccountDao accountDao = new AccountDaoImpl();
public void saveUser() {
accountDao.saveAccount();
}
}
测试一下:
// 1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 2.根据id获取对象
IAccountService accountService = (IAccountService) ac.getBean("accountService");
System.out.println(accountService);

还有三个注解
* @Controller:一般用在表现层
* @Service:一般用在业务层
* @Repository一般用在持久层
* 以上三个注解它们的作用与属性与Component是一模一样的。
* 它们三个是spring矿建为我们提供明确的三层使用,使我们的三层对象更加清晰
我们可以为AccountDaoImpl添加注解,把它装入spring的容器中:
/**
* 账户持久层实现类
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
public AccountDaoImpl(){
}
public void saveAccount() {
System.out.println("保存了账户");
}
}
测试一下
AccountDaoImpl accountDao = ac.getBean("accountDao", AccountDaoImpl.class);
System.out.println(accountDao);

注入数据的注解
@Component(value = "accountService")
public class AccountServiceImpl implements IAccountService {
public AccountServiceImpl(){
System.out.println("AccountServiceImpl被创建...");
}
private IAccountDao accountDao = null;
public void saveUser() {
accountDao.saveAccount();
}
}
当我想使用AccountServiceImpl中的saveUser()方法时,在测试中从IOC容器中取出AccountServiceImpl对象直接调用其saveUser()方法,会报空指针异常,因为AccountServiceImpl中的IAccountDao 对象为空。
我们使用 @Autowired 注解注入变量
* 注入数据的注解
* 他们的作用就和在xml配置文件的bean标签中<property>标签的作用是一样的
* @Autowired:
* 作用:自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
* 如果IOC容器中没有任何bean类型和要注入的变量类型匹配则报错
* 出现的位置:可以使变量上,也可以是方法上
在声明accountDao 变量的语句上加上注解
@Autowired
private IAccountDao accountDao;
再在测试从IOC容器中取出AccountServiceImpl对象直接调用其saveUser()方法
调用成功,证明自动注入成功了。
注意:如果IOC容器中没有任何bean类型和要注入的变量类型匹配则报错
如果IOC容器中有多个bean和要注入的变量类型匹配时:
spring会先去IOC容器中找和要注入的变量类型相同的bean,此时它找到了多个和要注入的变量类型相同的类型的bean。然后spring回去找bean的id,如果有id和要注入的变量的变量名相同,就将其注入到变量中;如果没有和要注入的变量的变量名相同的id,则报错
例有两个IAccountDao的实现类AccountDaoImpl和AccountDaoImpl2
// id是accountDao1
@Repository("accountDao1")
public class AccountDaoImpl implements IAccountDao {
public void saveAccount() {
System.out.println("保存了账户1111111");
}
}
// id是accountDao2
@Repository("accountDao2")
public class AccountDaoImpl2 implements IAccountDao {
public void saveAccount() {
System.out.println("保存了账户22222222");
}
}
在AccountServiceImpl类中IAccountDao类的变量名为accountDao,而在IOC容器中存在两个
和IAccountDao 匹配的bean,也就是上面的AccountDaoImpl和AccountDaoImpl2
@Component(value = "accountService")
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
public AccountServiceImpl(){
System.out.println("AccountServiceImpl被创建...");
}
public void saveUser() {
accountDao.saveAccount();
}
}
当我们运行测试:
// 1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 2.根据id获取对象
IAccountService accountService = (IAccountService) ac.getBean("accountService");
// 调用accountService方法
accountService.saveUser();
会报错,原因是我们IOC容器中有两个和IAccountDao 匹配的bean,但是这两个bean的id(accountDao1 和 accountDao2)没有一个和AccountServiceImpl中的IAccountDao 变量的变量名accountDao 相同,导致spring不知道该注哪个bean到变量中,就会报错
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountService': Unsatisfied dependency expressed through field 'accountDao'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.itheima.dao.IAccountDao' available: expected single matching bean but found 2: accountDao1,accountDao2
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountService': Unsatisfied dependency expressed through field 'accountDao'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.itheima.dao.IAccountDao' available: expected single matching bean but found 2: accountDao1,accountDao2
当我们把AccountServiceImpl中的IAccountDao 变量的变量名改为accountDao1时,此时运行测试,spring就能找到IOC容器中和IAccountDao 匹配的bean且这个bean的id和IAccountDao 变量的变量名一致,就会将这个id为accountDao1的bean注入到IAccountDao 中
@Autowired
private IAccountDao accountDao1;

同理把AccountServiceImpl中的IAccountDao 变量的变量名改为accountDao2时,就会将这个id为accountDao2的bean注入到IAccountDao 中
@Autowired
private IAccountDao accountDao2;
用于改变作用范围的注解
* 改变作用范围的注解
* 他们的作用就和在bean标签的scope属性的作用是一样的
* @Scope:
* 作用:用于指定bean的作用范围
* 属性:
* value:指定范围的值。
* 常用取值:
* singleton:单例(默认)
* prototype:多例
和生命周期相关的注解
* 和生命周期相关的注解
* 他们的作用就和在bean标签中init-method、destroy-method的作用是一样的
* @PostConstruct:用于指定初始化方法
* @PreDestroy:用于指定销毁方法
/**
* 账户持久层实现类
*/
@Repository("accountDao2")
public class AccountDaoImpl2 implements IAccountDao {
public void saveAccount() {
System.out.println("保存了账户22222222");
}
@PostConstruct
public void init(){
System.out.println("初始化方法执行");
}
@PreDestroy
public void destroy(){
System.out.println("销毁方法执行");
}
}
// 1.获取核心容器对象
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 2.根据id获取对象
IAccountService accountService = (IAccountService) ac.getBean("accountService");
accountService.saveUser();
ac.close();

案例使用xml方式实现表的CRUD操作
首先准备好数据库

然后创建项目,把实体类、持久层接口和业务层接口创建好
AccountServiceImpl:
package com.itheima.service.impl;
import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import com.itheima.service.IAccountService;
import java.util.List;
/**
* 账户业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao= null;
// accountDao的set方法,用于注入
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = 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);
}
}
AccountDaoImpl:
package com.itheima.dao.impl;
import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
/**
* 用户持久层实现类
*/
public class AccountDaoImpl implements IAccountDao {
private QueryRunner runner;
// runner的set方法,用于注入
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) {
e.printStackTrace();
return null;
}
}
public Account findAccountById(Integer id) {
try {
return runner.query("select * from account where id = ?",new BeanHandler<Account>(Account.class),id);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
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();
}
}
}
之后开始搭建spring环境:
首先pom中导入spring的依赖,然后resources中创建好spring的配置文件bean.xml添加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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
接下来就可以在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>
<!-- 配置数据源(c3p0) -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 注入连接数据库的必备信息 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="mysql://localhost:3306/eesy?serverTimezone=UTC"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>

案例使用注解方式实现表的CRUD操作
基于上面的案例进行改造:
1. spring.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="com.itheima"></context:component-scan>
<!-- QueryRunner -->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!-- 注入数据源(使用构造函数注入) -->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!-- 配置数据源(c3p0) -->
<bean name="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?serverTimezone=UTC&characterEncoding=utf-8&useUnicode=true"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
2. 将类表示为spring bean

3. 给需要注入的变量加上@Autowired注解

spring配置类(为了完全消除xml文件)
@Configuration
* @Configuration
* 作用:指定当前类是一个配置类
* 细节:当配置类作为AnnotationConfigApplicationContext对象创建对象时,该注解可以不写
@Configuration
public class SpringConfiguration {
}
@ComponentScan
* @ComponentScan
* 作用:用于通过注解指定spring在创建容器时要扫描的包
* 属性:
* value:和basePackages作用一样,都是用于指定在创建容器时要扫描的包(可以是大括号,配多个包)
* 使用该注解等同于在xml中配置了:
* <context:component-scan base-package="com.itheima"></context:component-scan>
@Configuration
@ComponentScan(basePackages = "com.itheima")
public class SpringConfiguration {
}

@Bean
* @Bean
* 作用:用于把方法的返回值作为bean对象存入spring的IOC容器中
* 属性:
* name:用于指定bean的id(不写时默认值是当前方法名)
* 细节:
* 当我们使用该注解配置方法时,如果方法有参数,spring会去容器中查找有没有可用的bean对象
* 查找的方式和@Autowired的作用是一样的,也就是自动按照类型注入,容器中有相同类型的bean时就根据bean的id筛选
@Configuration
@ComponentScan(basePackages = "com.itheima")
public class SpringConfiguration {
/**
* 用于创建一个QueryRunner对象
* @param dataSource
* @return
*/
@Bean(name = "runner")
public QueryRunner createQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
/**
* 创建数据源对象
* @return
*/
@Bean("dataSource")
public DataSource createDataSource() {
ComboPooledDataSource ds = new ComboPooledDataSource();
try {
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy?serverTimezone=UTC&characterEncoding=utf-8&useUnicode=true");
ds.setUser("root");
ds.setPassword("root");
return ds;
} catch (PropertyVetoException e) {
throw new RuntimeException(e);
}
}
}


此时我们的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">
</beans>
当我们使用的ApplicationContext的实现类是AnnotationConfigApplicationContext时,就可以删除bean.xml文件了
测试类:
@Test
public void findAllAccount() {
// 1.获取容器
// ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
// 2.获取对象
IAccountService accountService = ac.getBean("accountService", IAccountService.class);
// 3.执行方法
List<Account> accounts = accountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
执行后查询成功:
@Scope
与xml的bean标签中的scope属性作用一样
此时配置类中的SpringConfiguration的QueryRunner对象是单例的
使用 @Scope注解使其变成多例
@Import
当@Configuration作为AnnotationConfigApplicationContext对象创建对象时,该注解可以不写
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
什么情况下是必须注解的呢?
我们新建一个配置类JdbcConfig,里面放的是我们连接数据库的配置,也就是把SpringConfiguration里面的jdbc配置拿出来放进去
注意,此时JdbcConfig没有加@Configuration注解,它并非配置类
JdbcConfig:
public class JdbcConfig {
/**
* 用于创建一个QueryRunner对象
* @param dataSource
* @return
*/
@Bean(name = "runner")
@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
/**
* 创建数据源对象
* @return
*/
@Bean("dataSource")
public DataSource createDataSource() {
ComboPooledDataSource ds = new ComboPooledDataSource();
try {
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/eesy?serverTimezone=UTC&characterEncoding=utf-8&useUnicode=true");
ds.setUser("root");
ds.setPassword("root");
return ds;
} catch (PropertyVetoException e) {
throw new RuntimeException(e);
}
}
}
并在@ComponentScan注解上多加一个要扫描的包,也就是JdbcConfig所在的config包
SpringConfiguration:
@Configuration
@ComponentScan(basePackages = {"com.itheima","config"})
public class SpringConfiguration {
}
此时我们告诉了spring,JdbcConfig这个类也要扫描,但是我们运行时报错,ioc容器中找不到QueryRunner
扫描包的时候会扫描类,首先这个类必须是配置类才会把里面的bean装入IOC,也就必须加上@Configuration注解标识这个类是配置类
这个类如果是作为AnnotationConfigApplicationContext对象创建对象时传入的类字节码,该注解可以不写
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountDao': Unsatisfied dependency expressed through field 'runner'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.apache.commons.dbutils.QueryRunner' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
想要找到QueryRunner,就必须在JdbcConfig加上@Configuration
此时就可以成功运行。
如果不想写在JdbcConfig加上@Configuration,就在创建AnnotationConfigApplicationContext对象的时候也传入该类的字节码:
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class, JdbcConfig.class);
当加@Configuration和传创建AnnotationConfigApplicationContext对象的时候传入该类的字节码,就使用@Import注解
* @Import
* 作用:用于导入其他的配置类
* 属性:
* value:用于指定其他配置类的字节码
* 当我们使用Import的注解,有Import注解的类就是主配置类/父配置类,而导入的就是子配置类
在主配置类(有Import注解的类)上加上@Import注解
@Configuration
@ComponentScan(basePackages = {"com.itheima"})
@Import(JdbcConfig.class)
public class SpringConfiguration {
}
如果有多个配置类就可以在该注解里面加入多个配置类
此时运行测试类
@Test
public void findAllAccount() {
// 1.获取容器
// ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
// 2.获取对象
IAccountService accountService = ac.getBean("accountService", IAccountService.class);
// 3.执行方法
List<Account> accounts = accountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
运行成功
@PropertySource
不想把在子配置类JdbcConfig下的配置连接数据库信息写死
使用PropertySource注解
在resources目录下创建jdbcConfig.properties文件存放连接数据库的配置参数
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/eesy?serverTimezone=UTC&characterEncoding=utf-8&useUnicode=true
jdbc.username = root
jdbc.password = root
在子配置类JdbcConfig下创建变量
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
value注解里面的值必须和properties文件的key对应
然后JdbcConfig下的配置连接数据库信息可以写成这样,传入上面的变量
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
然后再主配置类加@PropertySource注解
* @PropertySource:
* 作用:用于指定properties文件的位置
* 属性:
* value:指定文件的名称和路径
* 关键字:classpath,表示类路径下(有包就写包,例:classpath:config/spring/jdbcConfig.properties)
在SpringConfiguration类加注解
@Configuration
@ComponentScan(basePackages = {"com.itheima"})
@Import(JdbcConfig.class)
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {
}
spring整合junit
* 使用junit单元测试:测试配置
* spring整合junit配置
* 1、导入整合junit的jar包
* 2、使用junit提供的注解把原有的main方法替换,替换成spring提供的main方法
* @RunWith
* 3、告知spring运行器,spring的IOC创建时基于xml配置文件还是基于注解,并说明位置
* @ContextConfiguration
* locations: 指定xml文件位置和classpath关键字,表示在类路径下
* classes: 指定注解类所在的位置
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
//@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
IAccountService accountService;
@Test
public void findAllAccount() {
// 3.执行方法
List<Account> accounts = accountService.findAllAccount();
for (Account account : accounts) {
System.out.println(account);
}
}
@Ignore
public void findAccountById() {
Account account = accountService.findAccountById(1);
System.out.println(account);
}
@Ignore
public void saveAccount() {
Account account = new Account();
account.setMoney(111f);
account.setName("彩脂");
accountService.saveAccount(account);
}
@Ignore
public void updateAccount() {
Account account = new Account();
account.setId(1);
account.setMoney(111f);
account.setName("彩脂");
accountService.updateAccount(account);
}
@Ignore
public void deleteAccount() {
accountService.deleteAccount(5);
}
}
来源:CSDN
作者:sSor
链接:https://blog.csdn.net/qq_41179691/article/details/103647489