@Configuration 指定当前类为配置类,类似于创建了spring的XML的beans配置文件
- 使用 AnnotationConfigApplicationContext获取配置类创建spring容器 ApplicationContext ac = new AnnotationConfigApplicationContext(配置类.class,配置类.class,。。。。。。);
- 当配置类作为AnnotationConfigApplicationContext的对象创建参数时,这个配置类可省略这个注解
- 如果不想写多个Configuration,并且不想在AnnotationConfigApplicationContext中添加多个参数,可以在主配置类中使用@Import("配置类.class")
@ComponentScan用于指定spring在创建容器时要扫描的包,
- 相当于XML的 <context:component-scan base-package="org.example"></context:component-scan> 配置
@Import 多个配置类用于导入其他配置类
属性:value:用于指定其他配置类的字节码
@Bean将当前方法的返回值作为bean对象存入spring的容器中
属性:name用于指定bean的ID, name可不写,默认值是当前方法的名称
当我们使用注解配置方法时,如果方法有参数,spring会去容器中查找有没有可用的bean对象,查找的方法和@Autowriter一致
@Scope("prototype")//指定单例还是多例
@Qualifier 有多个类型匹配时,如果根据ID匹配不上,默认使用其中一个
@PropertySource 加载配置文件
@PropertySource({"",""}) 加载多个配置文件
属性:value 默认,用于指定properties配置文件的位置和配置文件,关键字:classpth表示类路径下
@Value 使用EL表达式把配置文件中的值加载给成员变量,也可以直接字符串赋值,使用EL表达式,${}中为配置文件的key
代码示例
创建数据库表映射实体类
public class Account {
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 +
'}';
}
}
创建一个DAO查询类
public interface AccountDao {
List<Account> findAll();
Account findAccountById(Integer id);
void saveAccount(Account account);
void updateAccount(Account account);
void deleteAccount(Integer accountId);
}
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.example.dao.AccountDao;
import org.example.pojo.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class AccountDaoImpl implements AccountDao {
@Autowired
private QueryRunner queryRunner;
@Override
public List<Account> findAll() {
List<Account> query = null;
try {
query = queryRunner.query("select * from account", new BeanListHandler<>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
return query;
}
@Override
public Account findAccountById(Integer id) {
Account query = null;
try {
query = queryRunner.query("select * from account", new BeanHandler<Account>(Account.class));
} catch (Exception e) {
throw new RuntimeException(e);
}
return query;
}
@Override
public void saveAccount(Account account) {
try {
queryRunner.update("insert into account(name,money) values (?,?)", account.getName(), account.getMoney());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void updateAccount(Account account) {
try {
queryRunner.update("update account set name=?,money=? where id=?", account.getName(), account.getMoney(), account.getId());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteAccount(Integer accountId) {
try {
queryRunner.update("delete from account where id=?", accountId);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
数据库连接配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/xiaoqiang
jdbc.user=root
jdbc.password=Xiaoqiang1006
创建主配置类和数据库连接配置类
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
//@Configuration 指定当前类为配置类,类似于创建了spring的XML的beans配置文件
//使用 AnnotationConfigApplicationContext获取配置类创建spring容器 ApplicationContext ac = new AnnotationConfigApplicationContext(配置类.class,配置类.class,。。。。。。);
//当配置类作为AnnotationConfigApplicationContext的对象创建参数时,这个配置类可省略这个注解
//如果不想写多个Configuration,并且不想在AnnotationConfigApplicationContext中添加多个参数,可以在主配置类中使用@Import("配置类.class")
@Configuration
//@ComponentScan用于指定spring在创建容器时要扫描的包,
// 相当于XML的 <context:component-scan base-package="org.example"></context:component-scan> 配置
@ComponentScan(basePackages = {"org.example"})
//@Import 用于导入其他配置类
// 属性:value:用于指定其他配置类的字节码
@Import(JDBCConfiguration.class)
public class SpringConfiguration {
@Bean(name = "queryRunner")
//@Bean将当前方法的返回值作为bean对象存入spring的容器中
//属性:name用于指定bean的ID, name可不写,默认值是当前方法的名称
//当我们使用注解配置方法时,如果方法有参数,spring会去容器中查找有没有可用的bean对象,查找的方法和@Autowriter一致
@Scope("prototype")//指定单例还是多例
//@Qualifier 有多个类型匹配时,如果根据ID匹配不上,默认使用其中一个
public QueryRunner createQueryRunner(@Qualifier("dataSource1") DataSource dataSource) {
return new QueryRunner(dataSource);
}
}
package config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
//PropertySource 加载配置文件
// 属性value 默认,用于指定properties配置文件的位置和配置文件,关键字:classpth表示类路径下
@PropertySource("classpath:JDBC.properties")
//@PropertySource({"",""}) 加载多个配置文件
public class JDBCConfiguration {
//@Value 使用EL表达式把配置文件中的值加载给成员变量,也可以直接字符串赋值,使用EL表达式,${}中为配置文件的key
@Value("${jdbc.driver}")//EL表达式赋值
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("root")//直接赋值
private String user;
@Value("${jdbc.password}")
private String password;
@Bean(name = "dataSource1")
public DataSource createDataSource1() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(user);
dataSource.setPassword(password);
} catch (Exception e) {
throw new RuntimeException("创建数据源异常", e);
}
return dataSource;
}
@Bean(name = "dataSource2")
public DataSource createDataSource2() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(user);
dataSource.setPassword(password);
} catch (Exception e) {
throw new RuntimeException("创建数据源异常", e);
}
return dataSource;
}
}
service调用DAO
package org.example.service;
import org.example.pojo.Account;
import java.util.List;
public interface AccountService {
List<Account> findAll();
Account findAccountById(Integer id);
void saveAccount(Account account);
void updateAccount(Account account);
void deleteAccount(Integer accountId);
}
package org.example.service.impl;
import org.example.dao.AccountDao;
import org.example.dao.impl.AccountDaoImpl;
import org.example.pojo.Account;
import org.example.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public List<Account> findAll() {
return accountDao.findAll();
}
@Override
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
@Override
public void saveAccount(Account account) {
accountDao.saveAccount(account);
}
@Override
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
@Override
public void deleteAccount(Integer accountId) {
accountDao.deleteAccount(accountId);
}
public AccountDao getAccountDao() {
return accountDao;
}
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
}
测试类
package org.example.service;
import config.SpringConfiguration;
import junit.framework.TestCase;
import org.apache.commons.dbutils.QueryRunner;
import org.example.pojo.Account;
import org.junit.Before;
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;
public class AccountServiceTest extends TestCase {
public void testFindAll() {
//配置文件获取容器获取容器
//ApplicationContext ac = new ClassPathXmlApplicationContext("springBean.xml");
//注解配置类获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//获取service 对象
AccountService accountService = ac.getBean("accountService", AccountService.class);
List<Account> all = accountService.findAll();
for (Account account: all) {
System.out.println(account);
}
}
@Test
public void testScope() {
//配置文件获取容器获取容器
//ApplicationContext ac = new ClassPathXmlApplicationContext("springBean.xml");
//注解配置类获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//获取service 对象
QueryRunner queryRunner = ac.getBean("queryRunner", QueryRunner.class);
QueryRunner queryRunner1 = ac.getBean("queryRunner", QueryRunner.class);
System.out.println(queryRunner == queryRunner1);
}
@Test
public void testFindOne() {
//获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("springBean.xml");
AccountService accountService = ac.getBean("accountService", AccountService.class);
Account accountById = accountService.findAccountById(1);
System.out.println(accountById);
}
@Test
public void testFindSave() {
ApplicationContext ac = new ClassPathXmlApplicationContext("springBean.xml");
AccountService accountService = ac.getBean("accountService", AccountService.class);
Account account = new Account();
account.setName("ddd");
account.setMoney(100F);
accountService.saveAccount(account);
}
@Test
public void testFindUpdate() {
ApplicationContext ac = new ClassPathXmlApplicationContext("springBean.xml");
AccountService accountService = ac.getBean("accountService", AccountService.class);
Account account = new Account();
account.setName("ddd");
account.setMoney(10000F);
account.setId(4);
accountService.updateAccount(account);
}
@Test
public void testFindDelete() {
ApplicationContext ac = new ClassPathXmlApplicationContext("springBean.xml");
AccountService accountService = ac.getBean("accountService", AccountService.class);
Account account = new Account();
accountService.deleteAccount(4);
}
}