Spring中@Configuration、@ComponentScan和@Bean注解
程序员文章站
2022-05-21 22:45:15
...
@Configuration
作用:指定当前类是一个配置类。
@ComponentScan
作用:用于通过注解指定spring在创建容器时要扫描的包。
属性:
- value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。我们使用此注解就等同于在xml中配置了
<context:component-scan base-package="com.qublog"></context:component-scan>
- basePackages
@Bean
作用:用于把当前方法的返回值作为bean对象,存入spring的IoC容器中。
属性:
- name:用于指定bean的id,默认值是当前方法的名称。
细节:当我们使用注解配置方法时,如果方法有参数,spring框架会去容器中查找有没有可用的bean对象,查找的方式和Autowired注解的作用时一样的。
示例:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qublog</groupId>
<artifactId>spring02_account_anno_ioc_withoutxml</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
</project>
Account类:
package com.qublog.domain;
import java.io.Serializable;
//账户的实体类
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
AccountDao接口:
package com.qublog.dao;
import com.qublog.domain.Account;
import java.util.List;
//账户的持久层接口
public interface AccountDao {
//查询所有
List<Account> findAllAccount();
//查询一个
Account findAccountById(Integer id);
//保存
void saveAccount(Account account);
//更新
void updateAccount(Account account);
//删除
void deleteAccount(Integer id);
}
AccountDaoImpl类:
package com.qublog.dao.impl;
import com.qublog.dao.AccountDao;
import com.qublog.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
//账户的持久层实现类
@Repository(value = "accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private QueryRunner 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 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 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 id) {
try{
runner.update("delete from account where id=?;",id);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
AccountService接口:
package com.qublog.service;
import com.qublog.domain.Account;
import java.util.List;
//账户的业务层接口
public interface AccountService {
//查询所有
List<Account> findAllAccount();
//查询一个
Account findAccountById(Integer id);
//保存
void saveAccount(Account account);
//更新
void updateAccount(Account account);
//删除
void deleteAccount(Integer id);
}
AccountServiceImpl类:
package com.qublog.service.impl;
import com.qublog.dao.AccountDao;
import com.qublog.domain.Account;
import com.qublog.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
//账户的业务层实现类
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private 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);
}
}
SpringConfiguration类:
package config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
//该类是一个配置类,它的作用和bean.xml是一样的
//spring中的新注解:
//Configuration
//ComponentScan
@Configuration
@ComponentScan(basePackages = {"com.qublog"})
public class SpringConfiguration {
//用于创建一个QueryRunner对象
@Bean(name = "runner")
@Scope(value = "prototype")
public QueryRunner createQueryRunner(DataSource dataSource) {
return new QueryRunner(dataSource);
}
//创建数据源对象
@Bean(name = "dataSource")
public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.cj.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/springtest?serverTimezone=UTC");
ds.setUser("root");
ds.setPassword("1234");
return ds;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
AccountServiceTest类:
package com.qublog.test;
import com.qublog.domain.Account;
import com.qublog.service.AccountService;
import config.SpringConfiguration;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
//使用Junit单元测试,测试我们的配置
public class AccountServiceTest {
@Test
public void testFindAll() {
//获取容器
// ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//得到业务层对象
AccountService as = (AccountService) ac.getBean("accountService");
//执行方法
List<Account> accounts = as.findAllAccount();
for (Account account:accounts) {
System.out.println(account);
}
}
@Test
public void testFindOne() {
//获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//得到业务层对象
AccountService as = (AccountService) ac.getBean("accountService");
//执行方法
Account account = as.findAccountById(1);
System.out.println(account);
}
@Test
public void testSave() {
//获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//得到业务层对象
AccountService as = (AccountService) ac.getBean("accountService");
//执行方法
Account account = new Account();
account.setName("test anno");
account.setMoney(666f);
as.saveAccount(account);
}
@Test
public void testUpdate() {
//获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//得到业务层对象
AccountService as = (AccountService) ac.getBean("accountService");
//执行方法
Account account = as.findAccountById(4);
account.setMoney(23456f);
as.updateAccount(account);
}
@Test
public void testDelete() {
//获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//得到业务层对象
AccountService as = (AccountService) ac.getBean("accountService");
//执行方法
as.deleteAccount(4);
}
}
上一篇: 静态变量、实例变量初始化时机,以及子类隐藏父类成员时,创建子类对象的一些问题
下一篇: file_get_contents请求url接口,出现“request resource is not found”
推荐阅读
-
Spring框架中 @Autowired 和 @Resource 注解的区别
-
Spring 中 @Service 和 @Resource 注解的区别
-
浅谈Spring中@Import注解的作用和使用
-
Spring框架中 @Autowired 和 @Resource 注解的区别
-
荐 Spring-boot-study02-spring.xml配置文件注入组件和@Bean注解注入组件差别
-
spring注解中的@Autowired和@Component基本作用
-
Spring中@Autowired和@Qualifier注解的3个知识点小结
-
Spring中bean的初始化和销毁几种实现方式详解
-
配置spring两种方式,XML与注解(通过@Configuration实现bean注入)
-
Spring中为bean指定InitMethod和DestroyMethod的执行方法