문제

I wonder if there is a way to get @Required working when doing the configuration by annotations. I turned my configuration up-and-down and back again but nothing seems to work for me. I'm using Spring 3.1 My basic configuration looks like this:

@Configuration
public class SpringConfig {
    @Bean
    public MailSender mailSender() {
        MailSender MailSender = new MailSender();
        // mailSender.setBean(dlMailSender);
        return mailSender;
    }

    @Bean
    public MyBean myBean() {
        MyBean myBean = new MyBean();
        // setting som props
        return myBean;
    }
} 

MailSender is here:

@Configurable
public class MailSender {
    private MyBean myBean;
    @Required
    public void setMyBean(MyBean myBean) {
        this.myBean = myBean;
    }
}

I'm testing it with this junit:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringConfig.class }, loader = AnnotationConfigContextLoader.class)
public class MailSenderTest {
    @Test
    public void test_main_beans_exists() {
        // when  then  given
    }
}

Thanks for any help

도움이 되었습니까?

해결책

Short answer - this is not even theoretically possible.

When using XML-based, bean definitions with their dependencies are completely managed by application context. Spring is able to check, what is being set and what is not being set.

When using annotation-based configuration, you are setting the dependencies yourself. There is no way how Spring can even know what you are doing with the bean before returning it from the factory method.


If you want to check whether the bean is correctly initialized, use InitializingBean or @PostConstruct and implement self-checking method. Spring is doing this regularly in its own beans.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top