Spring+web结合方法
1.POP依赖导入
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
2.配置注解扫描器
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:component-scan base-package="com.uplooking.spring"/>
</beans>
3.使用注解注入
web.xml配置Springd提供的监听器
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
4.使用注解装配Bean
dao层:
1.@Repository===>类型注入
@Repository
public class FanDao{}
2.@Repository(“fanDao”)===>名称注入
@Repository("fanDao")
public class FanDao{}
servi层
1.类型注入
@Service("fansService")
public class FanService{
@Autowired
FanDao usersDao;
}
2.名称注入
@Service("fansService")
public class FanService{
@Autowired
@Qualifier("fanDao")
FanDao usersDao;
}
conrtroller层:
public class FansController extends HttpServlet {
FanService usersService;
protected void service(HttpServletRequest req, HttpServletResponse resp) {
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
userService = (UserService)applicationContext.getBean("fansService");
}
}