2016-07-12 3 views
0

에 난 내가 어떤 다른 방법없이 Account 클래스에 속성 @Component 퍼팅 (그리고없이 객체 AccountsDao accountsDao스프링 사용 @Autowired 필드 @Component

public class Account { 

    @Autowired 
    private AccountsDao accountsDao; 

을 사용할 필요가 있음을, 내 애플 리케이션 경우를 가지고 있지 그것을 봄 콩으로 표시하십시오).

애플 리케이션이 크고 객관적인 이유가 있습니다. Account은 스프링 빈이 아니어야하며 수동으로 초기화해야합니다.

나는 이것이 하나의 사례라는 것을 알고 있으며 일반적인 구조는 괜찮습니다.

할 방법이 있습니까?

답변

0

추가 SpringUtils.java

import org.springframework.beans.BeansException; 
import org.springframework.beans.factory.config.BeanFactoryPostProcessor; 
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; 

@Component 
public class SpringUtils implements BeanFactoryPostProcessor { 

    private static ConfigurableListableBeanFactory beanFactory; 

    @Override 
    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException { 
     // TODO Auto-generated method stub 
     SpringUtils.beanFactory = arg0; 
    } 

    public static <T> T getBean(Class<T> clz) throws BeansException { 
     T result = (T) beanFactory.getBean(clz); 
     return result; 
    } 

} 

사용

AccountsDao accountsDao = SpringUtils.getBean(AccountsDao.class); 
+0

감사합니다 이것은 내가 본 것 중에서 가장 좋은 옵션입니다 – user1935987

+1

이것은 봄을 사용할 때 가려고하는 Inversion of Control 패턴을 파괴합니다. 이제'Account'는 외부에서 가져 오는 대신 의존성을 수집합니다. 테스트에서'Account'가 사용될 때'SpringUtils'를 올바르게 설정하는 것을 기억해야하기 때문에,이 코드는 테스트하기가 더 어렵습니다. – FrontierPsychiatrist

0

스프링 컨텍스트를 프로그래밍 방식으로 가져 와서 AccountsDoa를 가져올 수 있습니다. Account 생성자에서 그렇게 할 수 있습니다. Spring get current ApplicationContext 두 번째 응답입니다.

0

Account 건설 시간에 AccountsDao을 사용할 수 있다면 직접 생성자 주입을 수행 할 수 있습니다.

public class Account { 

    private final AccountsDao accountsDao; 

    public Account(AccountsDao accountsDao) { 
     this.accountsDa = accountsDao; 
    } 
} 

@Configurable 이외에도 AspectJ가 필요하다는 것 외에는 내가 아는 한.

http://olivergierke.de/2009/05/using-springs-configurable-in-three-easy-steps/

Spring autowiring using @Configurable

+0

사용할 수없는 옵션에 있지입니다. – user1935987

1

당신이, 특히 어떤 BeanUtils (절대 안티 패턴)을하지 말아야하고있다 이유, 왜 이것이 defa에 의해 지원되지 않는지 ult. 당신이 정말로 DAO 필요한 경우,

public class Account { 
    public void doSomethingWithDao(AccountDao accountDao) { 
    // TODO do somthing with dao, but do not store it in a field 
    } 
} 

편집 같은 것을 할 : 여기 당신이 그것을 부를 것이다 어떻게입니다 :

@Component 
public class MyBusinessLogicClass { 
    @Autowired 
    private AccountDao accountDao; 

    public void doMyBusinessLogic(Account account) { 
    account.doSomethingWithDao(accountDao); 
    } 
} 
+0

나는 당신을 얻지 못했습니다. 그때부터 'AccountDao accountDao'를 얻을 수 있습니까? – user1935987

+0

필요한 곳에 accountDao 만 있습니다. 그것은 당신이 accountDao를 필요로하는지에 달려 있지만, Account의 외부 호출자는 accountDao를 주입하여 메소드의 컨텍스트에 대해서만 매개 변수로 Account에 부여합니다. –

관련 문제