2017-12-22 6 views
0

JPA 엔티티 리스너에 스프링 종속성을 주입해야합니다. 나는 @Configurable과 Spring의 AspectJ 위버를 javaagent로 사용하여 이것을 해결할 수 있다는 것을 알고있다. 그러나 이것은 해킹 해결책처럼 보인다. 내가하려는 일을 성취 할 다른 방법이 있습니까? 당신은JPA 엔티티 리스너에 대한 스프링 종속성 삽입

import org.springframework.context.ApplicationContext; 

수입이 솔루션을 시도 할 수 있습니다

@Component 
public final class BeanUtil { 

    private static ApplicationContext context; 

    private BeanUtil(ApplicationContext context) { 
     BeanUtil.context = context; 
    } 

    public static <T> T getBean(Class<T> clazz) throws BeansException { 

     Assert.state(context != null, "Spring context in the BeanUtil is not been initialized yet!"); 
     return context.getBean(clazz); 
    } 
} 
+2

당신이 정교한 수 있습니까? 그것은 나쁜 상황처럼 들리네 –

+1

[XY 문제] (https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) 때문에 Downvoted – Synch

+0

@NicoVanBelle 나는 User 엔티티가있다. , 저장하기 전에 암호 해쉬를 갖고 싶습니다. 해싱 클래스는 Spring 빈이므로, 엔티티에 주입해야합니다. – Krzaku

답변

1

또 다른 트릭은 당신이 관리되는 클래스에서뿐만 아니라, 모든 곳에서 스프링 빈을 사용하는 데 도움이 정적 메소드를 사용하여 유틸리티 클래스를 구현하는 것입니다 org.springframework.context.ApplicationContextAware;

공공 최종 클래스 AutowireHelper은 ApplicationContextAware를 구현 {

private static final AutowireHelper INSTANCE = new AutowireHelper(); 
private static ApplicationContext applicationContext; 

private AutowireHelper() { 
} 

/** 
* Tries to autowire the specified instance of the class if one of the specified beans which need to be autowired 
* are null. 
* 
* @param classToAutowire  the instance of the class which holds @Autowire annotations 
* @param beansToAutowireInClass the beans which have the @Autowire annotation in the specified {#classToAutowire} 
*/ 
public static void autowire(Object classToAutowire, Object... beansToAutowireInClass) { 
    for (Object bean : beansToAutowireInClass) { 
     if (bean == null) { 
      applicationContext.getAutowireCapableBeanFactory().autowireBean(classToAutowire); 
      return; 
     } 
    } 
} 

/** 
* @return the singleton instance. 
*/ 
public static AutowireHelper getInstance() { 
    return INSTANCE; 
} 

@Override 
public void setApplicationContext(final ApplicationContext applicationContext) { 
    AutowireHelper.applicationContext = applicationContext; 
} 

}

당신이 그런 일을 할 이유를 다음

@Autowired 
SomeService thatToAutowire; 

    AutowireHelper.autowire(this, this.thatToAutowire);//this in the method 
0

: