Spring注解开发
Spring原始注解
回顾以前的步骤
1.创建UserDao接口,UserDaoImpl实现UserDao
2.创建UserService接口,UserServiceImpl实现UseService
3.UserServiceImpl中创建私有成员变量userDao,创建set方法(注入)
4.在applicationContext中进行userDao和userService的bean配置
5.创建UserController类,调取userDao中的方法
注解
//<bean id="userDao2" class="com.itheima.spring.UserDao2Impl"></bean>
@Component("userDao2")
public class UserDao2Impl implements UserDao2{
@Override
public void save() {
System.out.println("save running!!");
}
}
//<bean id="userService2" class="com.itheima.spring.UserService2Impl">
//@Scope("prototype")
@Scope("singleton")
@Component("userService2")
public class UserService2Impl implements UserService2{
@Value("${driverClass}")
private String driver;//获取键的值,前提是xml文件中加载了jdbc.properties
//<property name="userDao2" ref="userDao2"></property>
@Autowired//也可以不注解Qualifier,Autowired是按照数据类型从Spring容器中进行匹配的
@Qualifier("userDao2")//是按照id的值从容器中进行匹配的,但是主要与Autowired仪器使用
private UserDao2 userDao2;
/*public void setUserDao2(UserDao2 userDao2){
this.userDao2=userDao2;
}*/
//用xml配置的话,set方法必须写;如果用注解,则不用写
@Override
public void save() {
userDao2.save();
}
}
运行之后会报错 No qualifying bean of type ‘com.itheima.spring.UserService2’ available,这是因为我们没有给Spring说明哪个地方有注解,所以我们在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.itheima"></context:component-scan>
//扫描com.itheima以及com.itheima下的子包
</beans>
**Spring新注解** 是用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下: ![在这里插入图片描述](https://img-blog.csdnimg.cn/6b5d9e2c6870419a9cea15067f752ee1.png)![在这里插入图片描述](https://img-blog.csdnimg.cn/9fd7b169e82b4591857045b67abd75d6.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBARGl2LjE0Mw==,size_20,color_FFFFFF,t_70,g_se,x_16)为了完全用注解取代xml配置文件,用注解代替标签
1.创建config包下面创建SpringConfiguration类
2.加注解@Configuration(标志该类是Spring的核心配置类)
3.加注解@ComponentScan(组件扫描)
4.加载配置文件@PropertySource(把location扔进去)
5.在内部写一DataSource为返回值的getDataSource,加注解@Bean
6.再创建一个DataSourceConfiguration类,把关于数据源相关的挪过去
7.SpringConfiguration类中加载DataSourceConfiguration,用@Import(要是多个用逗号,其实是一个数组)
8.UserController中创建app用AnnotationConfigApplicationContext
UserController 类
public class UserController {
public static void main(String[] args) {
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService2 userService2=app.getBean(UserService2.class);
userService2.save();
}
}
DataSourceConfiguration 类
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {
@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 Exception {
ComboPooledDataSource dataSource=new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
Connection connection = dataSource.getConnection();
return dataSource;
}
}
SpringConfiguration 类
@Configuration
@ComponentScan("com.itheima")
@Import({DataSourceConfiguration.class})
public class SpringConfiguration {
}
Spring整合Junit
1.导入spring继承junit的坐标
2.使用@Runwith注解替换原来的运行期
3.使用@ContextConfiguration指定配置文件或配置类
4.使用@Sutowired注入需要测试的对象
5.创建测试方法进测试
POM.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
测试类SpringJunitTest
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:application-Context.xml")//配置文件形式
@ContextConfiguration(classes = {SpringConfiguration.class})//纯注解形式
public class SpringJunitTest {
// @Autowired
// private UserService3 userService3;
@Autowired
private DataSource dataSource;
// @Test
// public void method(){
// userService3.save();
// }
@Test
public void method2() throws SQLException {
System.out.println(dataSource.getConnection());
}
}
Spring集成Web环境
需要在POM.xml中导入新的坐标
POM.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
UserServlet
public class UserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = app.getBean(UserService.class);
userService.save();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
web.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">
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.itheima.web.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/userServlet</url-pattern>
</servlet-mapping>
</web-app>
== ApplicationContext app = new ClassPathXmlApplicationContext(“applicationContext.xml”); == 仍存在多次创建的弊端,这里使用监听器来解决这一问题(web项目中)
1.创建新包listener,ContextLoaderListener类继承ServletContextListener接口
2.将Spring的应用上下文对象存储到ServletContext域中
3.web.xml中配置监听器
4.servlet中获取ServletContext对象,获取app
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>applicationContext.xml</param-value>
</context-param><!--为了可以解耦合,之后再配置文件中就可以更改-->
<listener>
<listener-class>com.itheima.listener.ContextLoaderListener</listener-class>
</listener>
UserServlet
public class UserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
// ServletContext servletContext = this.getServletContext();//这个也可以获得ServletContext对象
ServletContext servletContext = req.getServletContext();
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
// ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
UserService userService = app.getBean(UserService.class);
userService.save();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
ContextLoaderListener
public class ContextLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ServletContext servletContext = sce.getServletContext();
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
servletContext.setAttribute("app",app);
System.out.println("spring容器启动完毕");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
ServletContextListener.super.contextDestroyed(sce);
}
}
WebApplicationContextUtils
public class WebApplicationContextUtils {
public static ApplicationContext getWebApplicationContext(ServletContext sce){
return (ApplicationContext) sce.getAttribute("app");
}
}
以上繁琐的代码都已被Spring容器进行封装(我都打了半个小时的代码你告我这个)
Spring提供获取应用上下文的工具
(好家伙 原来我学了个源码)
为了使用Spring提供的工具,我们需要:
1.在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)
2.使用WebApplicationContextUtils获得应用上下文对象ApllicationContext
POM.xml中导入新坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
其余的跟山寨版无区别,只是导包时要注意