A. spring常用註解有哪些
springmvc常用註解標簽詳解
1、@Controller
在SpringMVC 中,控制器Controller 負責處理由DispatcherServlet 分發的請求,它把用戶請求的數據經過業務處理層處理之後封裝成一個Model ,然後再把該Model 返回給對應的View 進行展示。在SpringMVC 中提供了一個非常簡便的定義Controller 的方法,你無需繼承特定的類或實現特定的介面,只需使用@Controller 標記一個類是Controller ,然後使用@RequestMapping 和@RequestParam 等一些註解用以定義URL 請求和Controller 方法之間的映射,這樣的Controller 就能被外界訪問到。此外Controller 不會直接依賴於HttpServletRequest 和HttpServletResponse 等HttpServlet 對象,它們可以通過Controller 的方法參數靈活的獲取到。
@Controller 用於標記在一個類上,使用它標記的類就是一個SpringMVC Controller 對象。分發處理器將會掃描使用了該註解的類的方法,並檢測該方法是否使用了@RequestMapping 註解。@Controller 只是定義了一個控制器類,而使用@RequestMapping 註解的方法才是真正處理請求的處理器。單單使用@Controller 標記在一個類上還不能真正意義上的說它就是SpringMVC 的一個控制器類,因為這個時候Spring 還不認識它。那麼要如何做Spring 才能認識它呢?這個時候就需要我們把這個控制器類交給Spring 來管理。有兩種方式:
(1)在SpringMVC 的配置文件中定義MyController 的bean 對象。
(2)在SpringMVC 的配置文件中告訴Spring 該到哪裡去找標記為@Controller 的Controller 控制器。
2、@RequestMapping
RequestMapping是一個用來處理請求地址映射的註解,可用於類或方法上。用於類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。
3、@Resource和@Autowired
@Resource和@Autowired都是做bean的注入時使用,其實@Resource並不是Spring的註解,它的包是javax.annotation.Resource,需要導入,但是Spring支持該註解的注入。
4、@ModelAttribute和 @SessionAttributes
代表的是:該Controller的所有方法在調用前,先執行此@ModelAttribute方法,可用於註解和方法參數中,可以把這個@ModelAttribute特性,應用在BaseController當中,所有的Controller繼承BaseController,即可實現在調用Controller時,先執行@ModelAttribute方法。
@SessionAttributes即將值放到session作用域中,寫在class上面。
具體示例參見下面:使用 @ModelAttribute 和 @SessionAttributes 傳遞和保存數據
5、@PathVariable
用於將請求URL中的模板變數映射到功能處理方法的參數上,即取出uri模板中的變數作為參數。
6、@requestParam
@requestParam主要用於在SpringMVC後台控制層獲取參數,類似一種是request.getParameter("name"),它有三個常用參數:defaultValue = "0", required = false, value = "isApp";defaultValue 表示設置默認值,required 銅過boolean設置是否是必須要傳入的參數,value 值表示接受的傳入的參數類型。
7、@ResponseBody
作用: 該註解用於將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換為指定格式後,寫入到Response對象的body數據區。
使用時機:返回的數據不是html標簽的頁面,而是其他某種格式的數據時(如json、xml等)使用;
8、@Component
相當於通用的註解,當不知道一些類歸到哪個層時使用,但是不建議。
9、@Repository
用於註解層,在Impl類上面註解。
B. 如何在FILTER過濾器中注入SPRING的BEAN
<filter> <filter-name>DelegatingFilterProxy</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> <init-param> <param-name>targetBeanName</param-name> <param-value>myFilter</param-value> //自己抄過濾器的名字 </init-param> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter -mapping> <filter-name>DelegatingFilterProxy</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
C. 在Spring中怎麼攔截自定義的註解
@Aspect
@Component//加上這個
public class MyInterceptor {
@Pointcut("execution(public * com.newer.service.imp.PersonServiecBean.save*(..))")
private void anyMethod(){}
@After(value="anyMethod()")
public void doAccess(){
System.out.println("前置通知!!");
}
}
<bean id="personService" class="com.newer.service.impl.PersonServiecBean"/>
配置裡面把myInterceptor去掉
如果還不行 乾脆用xml的形式
<bean id="personService" class="com.newer.servic e.impl.PersonServiecBean"/>
<bean id="myInterceptor" class="com.newer.service.MyInterceptor" />
<aop:config>
<aop:aspect id="logAspect" ref="myInterceptor">
<aop:before method="before" pointcut=("execution(public * com.newer.service.imp.PersonServiecBean.save*(..))") />
</aop:aspect>
</aop:config>
D. spring在filter裡面怎麼獲取註解方式定義的bean
WebApplicationContext wac = WebApplicationContextUtils.(getServletContext()); 有WebApplicationContext 了對象了 spring託管來的自所有對象都可以拿到了。 當然不推薦這種方式,一般是注入的方式
E. 請教怎麼用Spring的註解方式把一個Bean注入到過濾器中
參考:
UsersConnectionRepository bean =
(UsersConnectionRepository)WebApplicationContextUtils.
(filterConfig.getServletContext()).
getBean("usersConnectionRepository");
下面是優化的寫法:
UsersConnectionRepository bean = WebApplicationContextUtils.
(filterConfig.getServletContext()).
getBean(UsersConnectionRepository.class);
F. spring中有沒有註解攔截器,只攔截註解
可以啊有關AOP@Aspect的切點注釋。列
// 切點注釋方法
@Aspect
public class VisitHistory {
/**
* @param JoinPoint
*/
@Before("@annotation(com.XXXX.Auth)") // 採用切點注釋
public void before(JoinPoint jp) {
// jp.getTarget(); //得到目標對象
// jp.getSignature().getName();//得到方法名
// jp.getArgs(); //得到方法參數
Class s = joinPoint.getSignature().getDeclaringType();
System.out.println(s);
Auth auth = (Auth) joinPoint.getSignature().getDeclaringType().getAnnotation(Auth.class);
RequestMapping rm = (RequestMapping) joinPoint.getSignature().getDeclaringType().getAnnotation(RequestMapping.class);
if (auth.flag()) {...}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
@Inherited
public @interface Auth {
/**
* @return
*/
public boolean flag() default false;
}
/* 代理方法 */
@Auth(flag = true)
@RequestMapping("/homepage")
public ModelAndView home(HttpServletRequest request) {
...
}
G. spring中有沒有註解攔截器,只攔截註解
spring攔截器只攔截path, 或者說方法名稱, 它並不知道註解, 但是比servletfilter豐富的事是,這里可以比較方便的做反射操作.
比如可以繼承HandlerInterceptorAdapter類 或者實現HandlerInterceptor介面,放過沒有指定註解的請求即可(前者要求只要override preHandle, 後者要實現postHandle,preHandle和afterCompletion)
舉個Adapter的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
* 2016/08/30
* @author sleest
*/
@Component
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
HandlerMethod hm = (HandlerMethod) handler;
Method method = hm.getMethod();
// 這里就可以處理某些註解下要做的事情或者放過
// Is Annotation On Method's Class
method.getDeclaringClass().isAnnotationPresent(RequestMapping.class);
// Is Annotation On Method
method.isAnnotationPresent(RequestMapping.class);
// Get Method Annotation, Perhaps null
RequestMapping requestMappingAt = method.getAnnotation(RequestMapping.class);
// Get Annnotation Attribute
requestMappingAt.name();
requestMappingAt.method();
// ...
return true;
}
}
H. 請教怎麼用Spring的註解方式把一個Bean注入到過濾器中
@Component public class UseCarmanager implements AssignmentHandler { @Autowired public BaseDao baseDao; } 在spring的配置文件里要配置 base-scan 包含 UseCarManager的包路徑。