まず、特定のパスにインターセプタをバインドして、問題の半分を解決できます。
2番目の問題は、要求されたPersonリソースへの参照を取得していることです。
public class PersonContext{
private static ThreadLocal<Person> context = new ThreadLocal<Person>();
public static Person getPerson(Person person){
return context.get();
}
public static void setPerson(Person person){
context.set(person);
}
public static void cleanUp(){
context.remove();
}
}
標準JPAエンティティリスナーがロードされた人への参照をバインドするために使用することができます:あなたがここにThreadLocalを使用して見て可能性があり
public class PersonListener{
@PostLoad
public void setContext(Person person){
PersonContext.set(person);
}
}
エンティティリスナーがエンティティに登録することができます。
を:あなたは現在のスレッドコンテキストにバインドされた人への参照を取得し、それに応じてヘッダを設定することができるインターセプタで
@Entity
@EntityListeners(PersonListener.class)
public class Person(){
}
最後に
public class PersonInterceptor extends HandlerInterceptorAdapter {
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
if(request.getMethod.equals("GET")){
Person person = PersonContext.getPerson();
response.addHeader("age", person.getAge());
}
PersonContext.cleanUp();
}
}
春データ休息とあなたのインターセプタを登録します。
@Bean
public MappedInterceptor myMappedInterceptor() {
return new MappedInterceptor(new String[]{"person/**"}, new PersonInterceptor());
}
問題:
- ポスト・ロード・リスナーにも他のパス上の人のすべての負荷に実行し、そう無害ますより良いものにする必要があります。クリーンアップを処理するために、すべてのパスに2番目のインターセプタを登録しますか?
代わりの方法として、インターセプタのデータベースを再クエリーする方法があります。したがって、上記のような迎撃何かに置き換えることができます:
public class PersonInterceptor extends HandlerInterceptorAdapter {
@Autowired
private PersonRepository repository;
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
if(request.getMethod.equals("GET")){
Long personID = //extract id by examining request.getServletPath();
Person person = repository.findOne(personID);
response.addHeader("age", person.getAge());
}
}
}
これは、追加のクエリのオーバーヘッドを持っているでしょうが、これはおそらく、それが第一レベルのキャッシュからフェッチであることを意味するべきOpenEntityManagerInViewFilterを構成することによって回避することが可能です。
https://stackoverflow.com/a/19265876/5380322 – Cepr0
インターセプタは特定のパスにマッピングすることができます。あなたのような何かができるよう
だからそれが見えます。 https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/handler/MappedInterceptor.html#getPathPatterns--あなたはまだその人への参照を取得する必要がありますしかし、年齢を取得 –
私はレコードの特定のヘッダーが必要だと述べた。 – codesmith