以IOC和AOP为内核的分层全栈轻量开源框架。
快速入门
创建mavenweb项目,pom文件中引入依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
</dependencies>
com.kdy.dao包下创建dao接口
public interface UserDao {
public void save();
}
com.kdy.dao.impl包下创建dao接口的实现类
public class UserDaoImpl implements UserDao {
@Override
public void save() {
System.out.println("is saving...");
}
}
resource目录下new一个xml config file->spring config文件,在<beans></beans>中加上
<bean id="userDao" class="com.kdy.dao.impl.UserDaoImpl"></bean>
com.kdy.demo包下创建测试demo类
public class UserDaoDemo {
public static void main(String[] args) {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao)app.getBean("userDao");
userDao.save();
}
}
getBean()是通过类的无参构造创建的实例。
右键运行这个demo类的main方法即可。
Spring配置文件
id:该Bean实例在Spring容器中的唯一标识 class:Bean的全限定名 scope:作用范围
scope:(1singleton单例,不写scope也默认单例;2prototype多例;3request为Web项目Spring创建bean对象后存入request域中;4session为存入session域;5global session为Portlet环境时相当session)。
单例模式singleton多次app.getBean("userDao")是同一个对象。在ApplicationContext加载配置文件时创建实例。生命周期同容器。
多例模式prototype多次app.getBean("userDao")不是同一个对象。在getBean时创建实例。生命周期同普通java对象,可被GC回收。
Junit
依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!--<scope>test</scope>--><!--如果加上test只在test目录中可用,在main目录中不可用-->
</dependency>
测试类中@Test
public class SpringTest {
@Test
public void test1(){
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao)app.getBean("userDao");
userDao.save();
}
}
Bean的三种实例化方式
无参构造方法实例化、工厂静态方法实例化、工厂实例方法实例化
无参构造方法实例化
getBean()是通过类的无参构造创建的实例。
工厂静态方法实例化
com.kdy.factory包下创建StaticFactory类
public class StaticFactory {
public static UserDao getUserDao(){
return new UserDaoImpl();
}
}
applicationContext.xml中<beans></beans>里创建静态工厂bean,指定工厂方法
<bean id="userDao" class="com.kdy.factory.StaticFactory" factory-method="getUserDao"></bean>
执行测试类即可
public class SpringTest {
@Test
public void test1(){
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao)app.getBean("userDao");
userDao.save();
}
}
工厂实例方法实例化
com.kdy.factory包下创建DynamicFactory类
public class DynamicFactory {
public UserDao getUerDao(){
return new UserDaoImpl();
}
}
applicationContext.xml中<beans></beans>里创建bean指定实例工厂bean和指定工厂方法
<bean id="factory" class="com.kdy.factory.DynamicFactory"></bean>
<bean id="userDao" factory-bean="factory" factory-method="getUerDao"></bean>
执行测试类即可
public class SpringTest {
@Test
public void test1(){
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao)app.getBean("userDao");
userDao.save();
}
}
Bean的依赖注入(DI)
DI是IOC的核心。userDao的bean注入给userService的bean可通过set方式和构造方法的方式。
set方式DI依赖注入
com.kdy.dao.impl包中创建UserDaoImpl实现UserDao
public class UserDaoImpl implements UserDao {
@Override
public void save() {
System.out.println("is saving...");
}
}
com.kdy.service.impl创建UserServiceImpl实现userService
如果不注入,需要在applicationContext.xml中声明userDao的bean和userService的bean,然后在userServiceImpl中去通过app.getBean获取dao的bean,然后使用。
通过set注入的话直接定义为userServiceImpl的属性再提供set方法通过spring配置文件进行set注入即可在userServiceImpl中直接使用该属性对象实例方法。
public class UserServiceImpl implements UserService {
//set方式依赖注入,需在被注入的类中定义需要注入的属性,并生成set方法
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void save() {
/* //既然userDao通过spring注入给userService,则可不用在下方通过上下文去拿实例化的userDao的bean了
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao)app.getBean("userDao");*/
userDao.save();
}
}
resource目录下的applicationContext.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">
<bean id="userDao" class="com.kdy.dao.impl.UserDaoImpl"></bean>
<!-- <bean id="userDao" class="com.kdy.factory.StaticFactory" factory-method="getUserDao"></bean>-->
<!-- <bean id="factory" class="com.kdy.factory.DynamicFactory"></bean>
<bean id="userDao" factory-bean="factory" factory-method="getUerDao"></bean>-->
<bean id="userService" class="com.kdy.service.impl.UserServiceImpl">
<!--set方式实现依赖注入-->
<property name="userDao" ref="userDao"></property><!--name需和UserServiceImpl中属性名一致。ref需和该配置文件中某个bean的id一致-->
</bean>
</beans>
除了上面的property方式set注入,也可通过p命名空间set注入,如下
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="com.kdy.dao.impl.UserDaoImpl"></bean>
<!--首先在上方引入p命名空间 xmlns:p="http://www.springframework.org/schema/p"
然后使用p:的方式注入其他bean作为该bean的属性-->
<bean id="userService" class="com.kdy.service.impl.UserServiceImpl" p:userDao-ref="userDao"></bean>
</beans>
在com.kdy.demo包中创建模拟controller的类
public class UserController {
public static void main(String[] args) {
/* UserServiceImpl userService = new UserServiceImpl();*/
//我们也将userServiceImpl接管给spring,上行代码变成下面代码
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService)app.getBean("userService");
userService.save();
}
}
运行main方法即可。
构造方法方式DI依赖注入
com.kdy.service.impl中的userServiceImpl
public class UserServiceImpl implements UserService {
//构造方法方式依赖注入,提供被注入的属性和生成有参无参构造方法
private UserDao userDao;
public UserServiceImpl() {
}
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void save() {
userDao.save();
}
}
resource下的applicationContext.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">
<bean id="userDao" class="com.kdy.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.kdy.service.impl.UserServiceImpl">
<constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>
</beans>
Bean依赖注入的数据类型
普通数据类型、引用数据类型、集合数据类型
普通数据类型注入
set方式注入普通数据类型演示
com.kdy.dao.impl的UserDaoImpl
public class UserDaoImpl implements UserDao {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public void save() {
System.out.println(name+":"+age);
System.out.println("is saving...");
}
}
resource下的applicationContext.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">
<bean id="userDao" class="com.kdy.dao.impl.UserDaoImpl">
<property name="name" value="zhangsan"/>
<property name="age" value="18"/>
</bean>
</beans>
com.kdy.demo中模拟controller类
public class UserController {
public static void main(String[] args) {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao= (UserDao)app.getBean("userDao");
userDao.save();
}
}
集合数据类型注入
list集合、map集合、properties集合
com.kdy.pojo包中创建User类,并提供set、get、和toStirng方法
public class User {
private String name;
private String addr;
}
com.kdy.dao.impl包中创建UserDaoImpl
public class UserDaoImpl implements UserDao {
private List<String> strList;
private Map<String, User> userMap;
private Properties properties;
public void setStrList(List<String> strList) {
this.strList = strList;
}
public void setUserMap(Map<String, User> userMap) {
this.userMap = userMap;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
public void save() {
System.out.println(strList);
System.out.println(userMap);
System.out.println(properties);
System.out.println("is saving...");
}
}
applicationContext.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">
<bean id="user1" class="com.kdy.pojo.User">
<property name="name" value="tom"/>
<property name="addr" value="beijing"/>
</bean>
<bean id="user2" class="com.kdy.pojo.User">
<property name="name" value="杰瑞"/>
<property name="addr" value="南京"/>
</bean>
<bean id="userDao" class="com.kdy.dao.impl.UserDaoImpl">
<property name="strList">
<list><!--如果集合元素是基本数据类型就使用value,如果是引用数据类似引用其他bean,就使用ref-->
<value>aaa</value>
<value>bbb</value>
<value>ccc</value>
</list>
</property>
<property name="userMap">
<map><!--基本数据类型就使用keyh和value,如果是引用数据类似引用其他bean,就使用key-ref和value-ref-->
<entry key="mapaaa" value-ref="user1"></entry>
<entry key="mapbbb" value-ref="user2"></entry>
</map>
</property>
<property name="properties">
<props>
<prop key="p1">ppp1</prop>
<prop key="p2">ppp2</prop>
<prop key="p3">ppp3</prop>
</props>
</property>
</bean>
</beans>
Spring配置文件
引入其他配置文件(分模块开发)
可以在主配置文件中引入其他配置文件
<import resource="applicationContext-xxx.xml”/>
ApplicationContext实现类
ClassPathXmlApplicationContext("applicationContext.xml")
FileSystemXmlApplicationContext("C:\\Users\\app\\IdeaProject\\SpringModule\\src\\main\\resouorce\\applicationContext.xml")
AnnotationConfigApplicationContext
getBean()方法的使用
spring配置中userServiceImpl类只有一个bean时可用getBean(userService.class)
配置文件userServiceImpl多个bean和id时,只能用getBean("userService1")这种。
Spring配置数据源
以C3P0和druid为例
手动测试c3p0和druid数据源连接
pom文件依赖
<?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>org.example</groupId>
<artifactId>SpringModule</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</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.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!--<scope>test</scope>--><!--如果加上test只在test目录中可用,在main目录中不可用-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8080</port>
<path>/SpringModule</path><!--虚拟目录-->
</configuration>
</plugin>
</plugins>
</build>
</project>
test目录下com.kdy.test包中创建DataSourceTest
public class DataSourceTest {
@Test
//测试手动创建c3p0数据源
public void test1() throws Exception{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("root123");
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
@Test
public void test2() throws Exception{
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root123");
DruidPooledConnection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
运行测试用例。
抽取配置数据库连接参数到properties文件中
resource目录下创建jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root123
test目录下的DataSource中加上以下测试用例
@Test
public void test3() throws Exception{
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
String driver = rb.getString("jdbc.driver");
String url = rb.getString("jdbc.url");
String username = rb.getString("jdbc.username");
String password = rb.getString("jdbc.password");
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
运行测试用例。
spring配置数据源
继上,applicationContext.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">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
<property name="user" value="root"></property>
<property name="password" value="root123"></property>
</bean>
</beans>
test目录的测试类DataSourceTest加上下面测试用例
@Test
public void test4() throws Exception {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = app.getBean(DataSource.class);
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
spring配置数据源-抽取jdbc配置文件
继上,在resource中创建jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root123
修改resource下的applicationContext.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">
<!--首先引入上面context命名空间xmlns:context="http://www.springframework.org/schema/context"和
http://www.springframework.org/schema/context http://www.springframework.org/schema/beans/spring-context.xsd-->
<context:property-placeholder location="classpath:jdbc.properties"/><!--引入配置文件,使用el获取-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
</beans>
运行上面的测试用例test4即可。
Spring注解开发
1Spring原始注解
原始注解用来替代<Bean>的配置
@Component写在普通类上实例化Bean、@Controller写在web层的类上实例化Bean、
@Service写在service层的impl类上实例化Bean、@Repository写在dao层类上实例化、
@Autowired写在字段上根据类型依赖注入、@Qualifier结合@Autowired根据名称注入、
@Resource写在字段上名称注入、@Value注入普通属性、@Scope标柱Bean作用范围、
@PostConstruct写在Bean的初始化方法上、@PreDestroy写在Bean的销毁方法上。
mavenWeb项目,pom文件中引入spring依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
jdbc.properties文件,用于在配置文件中property-placeholder加载后被@Value注解读取el
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root123
spring核心配置applicationContext.xml中开启组件扫描和引入jdbc.properties
<?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">
<!--首先引入上面context命名空间xmlns:context="http://www.springframework.org/schema/context"和
http://www.springframework.org/schema/context http://www.springframework.org/schema/beans/spring-context.xsd-->
<context:component-scan base-package="com.kdy"/><!--开启组件扫描-->
<context:property-placeholder location="classpath:jdbc.properties"/><!--引入配置文件,使用el获取。包括类中的@Value注解也可读取el表达式-->
</beans>
com.kdy.dao.impl中创建userDaoImpl
//@Component("userDao")
//@Component//不写参数,默认id为类名首字母小写
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Override
public void save() {
System.out.println("is saving...");
}
}
com.kdy.service.impl中创建userServiceImpl
//@Component//不写参数,默认id为类名首字母小写
@Service("userService")
//@Scope("prototype") @Scope("singleton") 不写@Scope也默认singleton
public class UserServiceImpl implements UserService {
@Value("${jdbc.username}")
private String username;
@Autowired//不写@Qualifier的话按类型注入
// @Qualifier("userDaoImpl")//UserDaoImpl的@Component不写参数,默认id为类名首字母小写
@Qualifier("userDao")
// @Resource("userDao")//@Resource(name="")等于@Autowired+@Qualifier,根据bean的名称id注入
private UserDao userDao;//不需要提供set方法,注解输入通过反射注入
@Override
public void save() {
System.out.println(username);
userDao.save();
}
//测试@PostConstruct注解,会在web应用启动,spring容器创建时,实例化本bean时调用
@PostConstruct
public void init(){
System.out.println("service对象初始化方法");
}
//测试@PreDestroy,会在web应用关闭,spring容器销毁时,销毁本bean前调用
@PreDestroy
public void destroy(){
System.out.println("service对象销毁方法");
}
}
模拟controller:userController
public class UserController {
public static void main(String[] args) {
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
// UserService userService = (UserService) app.getBean("userServiceImpl");//@Component不加参数默认id为类名小写
UserService userService = app.getBean(UserService.class);
userService.save();
app.close();//关闭web应用,会销毁spring容器,会执行到userServiceImpl中写的销毁方法
}
}
1Spring新注解
配置c3p0数据源的bean"com.mchange.v2.c3p0.ComboPooledDataSource"第三方类我们无法通过上面旧注解注入属性,需使用新注解
@Configuration写在配置类上,指明为spring配置类,创建容器时会从该类加载注解。
@ComponentScan写在配置类上声明spring容器初始化的包扫描。
@Bean写在方法上,方法返回值作为bean存放容器中。
@PropertySource写在配置类上,声明用于加载.properties文件
@Import写在配置类上,用于导入spring的其他配置类。
mavenWeb项目pom文件引入spring、mysql、c3p0依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
resource下jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root123
resource下applicationContext.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">
</beans>
com.kdy.config包下spring核心配置类
@Configuration//声明该类为spring配置类
@ComponentScan("com.kdy")//声明包扫描
@PropertySource("classpath:jdbc.properties")
//@Import({DataSourceConfiguration.class,XXX.class})//引入其他声明的配置类:引入多个写个大括号,里面逗号隔开
public class SpringConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public DataSource getDataSource() throws PropertyVetoException{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
com.kdy.dao.impl下UserDaoImpl
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Override
public void save() {
System.out.println("is saving...");
}
}
com.kdy.service.impl下userServiceImpl
@Service("userService")
public class UserServiceImpl implements UserService {
@Value("${jdbc.username}")
private String username;
@Autowired
@Qualifier("userDao")
private UserDao userDao;//不需要提供set方法,注解注入通过反射方式注入
@Resource(name = "dataSource")
private DataSource dataSource;
@Override
public void save() throws SQLException {
System.out.println(username);
System.out.println(dataSource.getConnection());
userDao.save();
}
}
模拟controller在com.kdy.demo下UserController
public class UserController {
public static void main(String[] args) throws SQLException {
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = app.getBean(UserService.class);
userService.save();
}
}
运行上面main方法即可。
Spring集成Junit
原始junit问题:每个测试用例的方法中都有以下两行代码:
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = app.getBean(DataSource.class);
pom文件中引入junit和spring-test依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
test目录中写测试类加上@RunWith和@ContextConfiguration,注容器中的bean,即可使用:
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")//配置文件的方式
@ContextConfiguration(classes = {SpringConfiguration.class})//全注解的方式
public class SpringJunitTest {
@Autowired
private UserService userService;
@Test
public void test1() throws SQLException {
userService.save();
}
}
Spring集成web环境
创建mavenWeb项目模块,pom文件引入spring、junit、spring-test、servlet、jsp依赖
<?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>org.example</groupId>
<artifactId>SpringModule</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8080</port>
<path>/SpringModule</path><!--虚拟目录-->
</configuration>
</plugin>
</plugins>
</build>
</project>
com.kdy.dao.impl包创建userDao
public class UserDaoImpl implements UserDao {
@Override
public void save() {
System.out.println("is saving...");
}
}
com.kdy.service.impl包中创建userService
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void save() {
userDao.save();
}
}
resource目录下applicationContext.xml中配置bean和注入
<?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">
<bean id="userDao" class="com.kdy.dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="com.kdy.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
web.xml中我们定义一个全局初始化参数contextConfigLocation值为applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param><!--配置一个全局初始化参数,即application域的初始化参数,
在web的servlet类(即继承HttpServlet的类,通过this.getServletContext可获取servletContext)的代码中通过
servletContext.getInitParameter("contextConfigLocation)获取,
也可在jsp中通过el表达式直接获取-->
<param-name>contextConfigLocation</param-name>
<param-value>applicationContext.xml</param-value>
</context-param>
</web-app>
com.kdy.listener包下创建servletContext监听器
@WebListener
public class ContextLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
//获取web.xml中配置的application的全局初始化参数:
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");//其值为applicationContext.xml
ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
servletContext.setAttribute("app",app);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
为了不在servlet中写死数据,所以再次抽取一个工具类,解释如下:
之前servlet中从死数据"applicationContext.xml"获取app被监听器和web.xml初始化参数解耦了,但servlet中还需要servletContext.getAttribute("app")拿到,这里的"app"还是死数据,所以我们用一个工具类直接拿到这个applicaiton,避免在项目代码mvc层代码中写死数据了。
在com.kdy.util包下创建返回application的工具类
public class WebApplicationContextUtils {
public static ApplicationContext getApplicationContext(ServletContext servletContext){
return (ApplicationContext)servletContext.getAttribute("app");
}
}
com.kdy.web包中创建servlet
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = app.getBean(UserService.class);
上述注释的代码的这种方式,每次访问该servlet会重复创建很多次applicationContext对象,
web容器tomcat启动后为每一个web应用创建上下文对象servletContext,我们可用使用web监听器
ServletContextListener来当web应用启动时创建一个让其new一个应用上下文对象app通过setAttribute放入servletContext域对象中,
之后再通过ServletConfig.getServletContext或this.getServletContext的getAttribute取到该app对象。
*/
ServletContext servletContext = this.getServletContext();
ApplicationContext app = WebApplicationContextUtils.getApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);
userService.save();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}