2. Spring注解开发
2.1 Spring原始注解
Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xmI配置文件可以简化配置,提高开发效率。
Spring原始注解主要是替代<Bean>的配置:
@Component 使用在类上用于实例化Bean
@Controller 使用在web层类上用于实例化Bean
@Service 使用在service层类上用于实例化Bean
@Repository 使用在dao层类上用于实例化Bean
@Autowired 使用在字段上用于根据类型依赖注入
@Qualifier 结合@Autowired一起使用用于根据名称进行依赖注入
@Resource 相当于@Autowired+@Qualifier,按照名称进行注入
@Value 注入普通属性
@Scope 标注Bean的作用范围**
@PostConstruct 使用在方法上标注该方法是Bean的初始化方法
@PreDestroy 使用在方法上标注该方法是Bean的销毁方法
注意:使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及好包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法。
<!--注解的组件扫描->
<context:component-scanbase-package="com.jian</context:component-scan>
packagecom.jian.dao;
publicinterfaceUserDao {
publicvoidsave();
}
packagecom.jian.dao.Impl;
importcom.jian.dao.UserDao;
importorg.springframework.stereotype.Component;
importorg.springframework.stereotype.Repository;
//<bean id="userDao" class="com.jian.dao.Impl.UserDaoImpl"></bean>
//@Component("userDao")
@Repository("userDao")
publicclassUserDaoImplimplementsUserDao {
publicvoidsave() {
System.out.println("sava runing...");
}
}
packagecom.jian.service;
publicinterfaceUserService {
publicvoidsave();
}
packagecom.jian.service.Impl;
importcom.jian.dao.UserDao;
importcom.jian.service.UserService;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Qualifier;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.context.annotation.Scope;
importorg.springframework.stereotype.Component;
importorg.springframework.stereotype.Repository;
importorg.springframework.stereotype.Service;
importjavax.annotation.PostConstruct;
importjavax.annotation.PreDestroy;
importjavax.annotation.Resource;
//<bean id="userService" class="com.jian.service.Impl.UserServiceImpl">
//@Component("userService")
@Service("userService")
//@Scope("prototype")
@Scope("singleton")
publicclassUserServiceImplimplementsUserService {
@Value("${jdbc.driver}")
privateStringdriver;
// <property name="userDao" ref="userDao"></property>
//@Autowired//按照数据类型从Spring容器中进行匹配的
//@Qualifier("userDao")//按照id值从Spring容器中匹配的,但是主要此处@Qualifier结合@Aoutwired一起使用
@Resource(name="userDao")//@Resource相当于@Qualifier+@Aoutwired
privateUserDaouserDao;
/* public void setUserDao(UserDao userDao){
this.userDao=userDao;
}*/
publicvoidsave() {
System.out.println(driver);
userDao.save();
}
@PostConstruct
publicvoidinit(){
System.out.println("Service对象的初始化方法");
}
@PreDestroy
publicvoiddestory(){
System.out.println("Service对象的销毁方法");
}
}
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.15</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.23</version>
</dependency>
//模拟web层
packagecom.jian.web;
importcom.jian.service.UserService;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
publicclassUserController {
publicstaticvoidmain(String[] args) {
ClassPathXmlApplicationContextapp=newClassPathXmlApplicationContext("applicationContext.xml");
UserServiceuserService=app.getBean(UserService.class);
userService.save();
app.close();
}
}
2.2 Spring新注解
使用上面的注解还不能全部替代xm配置文件,还需要使用注解替代的配置如下:
●非自定义的Bean的配置: <bean>
●加载properties文件的配置:
context:property-placeholder
●组件扫描的配置:
context:component-scan
●引入其他文件: <import>
注解:
@Configuration用于指定当前类是一个 Spring配置类,当创建容器时会从该类上加载注解@ComponentScan
1.作用和在Spring的xml配置文件中的
2.用于指定Spring在初始化容器时要描的包。
3.<context:component-scan base-package= "com.itheima"/>一样
@Bean使用在方法上,标注将该方法的返回值存储到Spring容器中
@PropertySource用于加载.properties文件中的配置
@Import用于导入其他配置类
替代:
packagecom.jian.config;
importcom.mchange.v2.c3p0.ComboPooledDataSource;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.PropertySource;
importjavax.sql.DataSource;
//<context:property-placeholder location="classpath:jdbc.properties"/>
@PropertySource("classpath:jdbc.properties")
publicclassDataSourceConfiguration {
@Value("${jdbc.driver}")
privateStringdriver;
@Value("${jdbc.url}")
privateStringurl;
@Value("${jdbc.username}")
privateStringusername;
@Value("${jdbc.password}")
privateStringpassword;
@Bean("dataSource") //Spring会将当前方法的返回值以指定名称储存到Spring容器中
publicDataSourcegetDatasource(){
ComboPooledDataSourcedataSource=newComboPooledDataSource();
dataSource.setDataSourceName(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
returndataSource;
}
}
package com.jian.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
//标志该类是Spring的核心配置类
@Configuration
//<context:component-scan base-package="com.jian"/>
@ComponentScan("com.jian")
//<import resource=""/>
@Import(DataSourceConfiguration.class)
public class SpringConfiguration {
}
package com.jian.web;
import com.jian.config.SpringConfiguration;
import com.jian.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class UserController {
public static void main(String[] args) {
//ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
ApplicationContext app=new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService= app.getBean(UserService.class);
userService.save();
}
}
3. Spring集成Junit
3.1 原始Junit测试Spring的问题
在测试类中,每个测试方法都有以下两行代码:
ApplicationContextac=newClassPathXmlApplicationContext ("bean.xm1") ;
IAccountServiceas=ac.getBean ("accountService",IAccountService.class) ;
age:
ApplicationContextapp=newAnnotationConfigApplicationContext(SpringConfiguration.class);
UserServiceuserService=app.getBean(UserService.class);
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。
3.2 上述问题解决思路
让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它将需要进行测试Bean直接在测试类中进行注入
3.3 Spring集成Junit步骤
①导入spring集成Junit的坐标②使用@Runwi th注解替换原来的运行期③使用@ContextConfiguration指定配置文件或配置类④使用@Autowi red注入需要测试的对象⑤创建测试方法进行测试