目录
1.spring常用注解
Spring常用注解主要是替代<bean>
的配置。
IOC:控制反转
- @Component 就是把对象交给IOC,以下这三个注解是@Component的子注解
@Component("这个对象的id值") // 如果没有执行默认是当前类名首字母小写
- @Repository 在dao层上使用
- @Service 在业务上使用
- @Controller 在web层上使用
这些注解是可以混用的,但是这些注解如果想生效那么必须扫描到才可以
Dependency Injection :DI 依赖注入
- @Autowired 根据类型注入,如果这个类型下有多个实现类时就会有问题,可以结合@Qualifies使用
- @Qualifies 不能单独使用,一定要配合@Autowired使用 根据名称(id值)匹配
- @Resource(name="beanId") 就是根据名称注入,如果没有指定名称,默认使用的就是这个属性名称
Resource就是单纯的根据名称注入,默认使用的名称就是这个属性名称
Autowired就是单纯的根据类型注入,有多个实现类时就会有问题必须要结合@Qualifies使用
其他注解
- @Scope 相当于 scope="" 范围配置
- @PostConstruct 相当于 init-method="" 对象初始化时执行。
- @PreDestroy 相当于 destroy-method="" 对象销毁时执行
pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
</dependencies>
<properties>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.study"/>
<!--<bean id="userDao" class="com.study.dao.impl.UserDaoImpl">-->
<!--</bean>-->
<!--<bean id="accountService" class="com.study.service.impl.UserServiceImpl">-->
<!--<property name="userDao" ref="userDao"></property>-->
<!--</bean>-->
</beans>
测试类
public class UserDemo {
@Test
public void save(){
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = app.getBean(UserService.class);
userService.save();
app.close();
}
}
service接口
public interface UserService {
void save();
}
service实现类
@Service
public class UserServiceImpl implements UserService {
/*@Autowired
@Qualifier("userDaoImpl")*/
/*@Resource(name = "userDaoImpl")*/
/*private UserDao userDao;*/
@Resource
private UserDao userDaoImpl;
/* public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}*/
public void save() {
/*userDao.save();*/
userDaoImpl.save();
}
@PostConstruct
public void init(){
System.out.println("UserServiceImpl初始化");
}
@PreDestroy
public void destroy(){
System.out.println("UserServiceImpl销毁");
}
}
dao接口
public interface UserDao {
void save();
}
dao实现类
@Repository
public class UserDaoImpl implements UserDao {
public void save() {
System.out.println("执行了UserDaoImpl的save方法");
}
}
@Repository
public class PeopleDaoImpl implements UserDao {
@Override
public void save() {
}
}
2.使用Spring注解整合DbUtils
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.study"/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="dataSource"/>
</bean>
</beans>
测试类
public class TestDemo {
@Test
public void save() {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = app.getBean(AccountService.class);
Account account = new Account();
account.setName("jiujiu");
account.setMoney(1000.00);
accountService.save(account);
}
@Test
public void update() {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = app.getBean(AccountService.class);
Account account = new Account();
account.setId(4);
account.setName("lili");
account.setMoney(2000.00);
accountService.update(account);
}
@Test
public void delete() {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = app.getBean(AccountService.class);
accountService.delete(4);
}
@Test
public void findById() {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = app.getBean(AccountService.class);
System.out.println(accountService.findById(4));
}
@Test
public void findAll() {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = app.getBean(AccountService.class);
System.out.println(accountService.findAll());
}
}
service接口
public interface AccountService {
public void save(Account account);
public void delete(Integer id);
public void update(Account account);
public Account findById(Integer id);
public List<Account> findAll();
}
service实现类
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Override
public void save(Account account) {
// AccountDao accountDao = new AccountDaoImpl();
accountDao.save(account);
}
@Override
public void delete(Integer id) {
// AccountDao accountDao = new AccountDaoImpl();
accountDao.delete(id);
}
@Override
public void update(Account account) {
// AccountDao accountDao = new AccountDaoImpl();
accountDao.update(account);
}
@Override
public Account findById(Integer id) {
// AccountDao accountDao = new AccountDaoImpl();
return accountDao.findById(id);
}
@Override
public List<Account> findAll() {
// AccountDao accountDao = new AccountDaoImpl();
return accountDao.findAll();
}
}
dao接口
public interface AccountDao {
public void save(Account account);
public void delete(Integer id);
public void update(Account account);
public Account findById(Integer id);
public List<Account> findAll();
}
dao实现类
@Repository
public class AccountDaoImpl implements AccountDao {
@Autowired
private QueryRunner queryRunner;
@Override
public void save(Account account) {
try {
// QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
String sql = "insert into account (name,money) values (?,?)";
queryRunner.update(sql,account.getName(),account.getMoney());
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void delete(Integer id) {
try {
// QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
String sql = "delete from account where id = ?";
queryRunner.update(sql,id);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void update(Account account) {
try {
// QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
String sql = "update account set name = ? , money = ? where id = ?";
queryRunner.update(sql,account.getName(),account.getMoney(),account.getId());
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public Account findById(Integer id) {
Account account = null;
try {
// QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
String sql = "select * from account where id = ?";
account = queryRunner.query(sql, new BeanHandler<>(Account.class), id);
} catch (SQLException e) {
e.printStackTrace();
}
return account;
}
@Override
public List<Account> findAll() {
List<Account> accounts = null;
try {
// QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
String sql = "select * from account";
accounts = queryRunner.query(sql, new BeanListHandler<>(Account.class));
} catch (SQLException e) {
e.printStackTrace();
}
return accounts;
}
}
3.使用纯注解整合DbUtils
- @Configuration : 定义当前类是一个配置类 相当于一个applicationContext.xml
- @Bean 用来给第三方类创建对象的 QueryRunner DataSource
- @PropertySource 引入第三方的配置文件 <context:property-placeholder//>
- @ComponentScan 相当于 <context:component-scan/>
- @Import 相当于 <import resource="applicationContext-dao.xml"/>
- @Value 从第三方配置文件中取值
配置类
@Configuration
@ComponentScan("com.study")
@Import({DataSourceConfig.class,QueryRunnerConfig.class})
public class SpringConfig {
}
@Configuration
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfig {
@Value("${jdbc.driver}")
private String driverClassName;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource createDataSource(){
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driverClassName);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
@Configuration
public class QueryRunnerConfig {
@Bean
public QueryRunner createQueryRunner(@Autowired DataSource ds){
QueryRunner queryRunner = new QueryRunner(ds);
return queryRunner;
}
}
测试类
public class TestDemo {
@Test
public void findAll() {
// ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService accountService = app.getBean(AccountService.class);
System.out.println(accountService.findAll());
}
}
其余类不需要动
4.spring整合junit
Junit是一个单元测试工具,点击run的执行测试方法时,其实底层是通过runner(运行器)来工作的,默认的Junit是不会自动加载spring环境。
如果想在Junit中直接获取spring的容器,我们需要导入spring提供的测试整合包,切换为spring的运行器,就可以直接获取IOC容器中的对象了。
测试类
@RunWith(SpringRunner.class)//设置启动类为spring提供的启动类
//@ContextConfiguration(locations = "classpath:applicationContext.xml")//设置配置文件
@ContextConfiguration(classes = SpringConfig.class)//设置配置类
public class TestDemo {
@Autowired
AccountService accountService;
@Test
public void findAll() {
// AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(SpringConfig.class);
// AccountService accountService = app.getBean(AccountService.class);
System.out.println(accountService.findAll());
}
}
其余类不改变