spring的一些注解
要使用spring注解首先肯定要用scanner,spring配置文件中要有
<context:annotation-config />
<context:component-scan base-package="com.neu" />
其中com.neu就是要扫描的包
但是必须有下面的xmlns:context以及最后3个schema
<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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
然后项目中就可以使用注解了
1、@Controller用于标注控制层组件(如struts中的action) ,控制器(注入服务)
2、@Service用于标注业务层组件 ,service 服务(注入dao)
3、@Repository用于标注数据访问组件,即DAO组件,@repository dao(实现dao访问)
4、@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。 @component (把普通pojo实例化到spring容器中,相当于配置文件中的)
被注解的类会纳入进spring容器中管理。
还可以自己写个Servlet代理
/**
* 我们自己实现的一个代理类用于将Servlet转为Spring管理的Servlet Bean
*/
public class ServletToBeanProxy extends GenericServlet {
private String targetBean;//当前客户端请求的Servlet名字
private Servlet proxy;//代理Servlet
@Override
public void init() throws ServletException {
super.init();
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); //初始化Spring容器
this.targetBean = getServletName();
this.proxy = (Servlet) wac.getBean(targetBean);//调用ServletBean
proxy.init(getServletConfig());//调用初始化方法将ServletConfig传给Bean
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
proxy.service(arg0, arg1);//在service方法中调用bean的service方法,servlet会根据客户的请求去调用相应的请求方法(Get/Post)
}
}
然后web.xml中将所有的servlet都写成这样的:
<servlet>
<servlet-name>ServantInfoAction</servlet-name>
<servlet-class>com.gjp.o2o.controller.ServletToBeanProxy</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServantInfoAction</servlet-name>
<url-pattern>/ServantInfoAction</url-pattern>
</servlet-mapping>
就是将普通的servlet转移到这个代理。
然后所有普通的servlet都使用@controller就实现了