写在前面
Spring集成Junit
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class, UserServiceConfiguration.class})
public class SpringJuintTest {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
@Test
public void test() {
userService.save();
}
@Test
public void test1() throws SQLException {
System.out.println(dataSource.getConnection());
}
}
Spring集成web
- 加载慢用
archetypeCatalog=internal
- 监听器调用服务类
public class ContextLoaderListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(UserConfiguration.class);
ServletContext servletContext = sce.getServletContext();
servletContext.setAttribute("app",app);
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
<!--配置监听器-->
<listener>
<listener-class>com.java.listener.ContextLoaderListener</listener-class>
</listener>
//读取web.xml的全局参数
ServletContext servletContext = sce.getServletContext();
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
AnnotationConfigApplicationContext app = null;
try {
app = new AnnotationConfigApplicationContext(Class.forName(contextConfigLocation));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.java.UserConfiguration</param-value>
</context-param>
public static ApplicationContext getWebApplicationContext(ServletContext servletContext) {
return (ApplicationContext) servletContext.getAttribute("app");
}
Spring监听器
- web.xml配置监听器
- 使用spring内部的监听器和上下文工具类
- 配置
<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>
ServletContext servletContext = this.getServletContext()
//使用spring的工具类获取
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext)
UserService bean = app.getBean(UserService.class)
bean.save()