1

I'm new to Java config. I have a code like this. SomeDao has its own dependency, shouldn't we set the dependencies since we are doing new? Can someone please help me understand this code?

@Configuration
public class DAOConfiguration {
    @Bean(name = "someDao")
    public SomeDao someDao() {
        return new SomeDao();
    }

1 Answer 1

2

Are you familiar with how this is done in xml? It is extremely similar to that.

Here is an example of SomeDao being configured with Dep1 (via constructor injection) and Dep2 (via setter injection) in xml:

<bean id="someDao" class="com.example.SomeDao">
  <constructor-arg ref="dep1"/>
  <property name="dep2" ref="dep2"/>
</bean>

<bean id="dep1" class="com.example.Dep1" />
<bean id="dep2" class="com.example.Dep2" />

This same example in JavaConfig would be configured as such:

@Configuration
public class DAOConfiguration {
    @Bean(name = "someDao")
    public SomeDao someDao() {
        final SomeDao someDao = new SomeDao(dep1());
        someDao.setDep2(dep2());
        return someDao;
    }

    @Bean(name="dep1")
    public Dep1 dep1() {
        return new Dep1();
    }

    @Bean(name-"dep2")
    public Dep2 dep2() {
        return new Dep2();
    }
}

All three beans are still registered with the ApplicationContext too, so you can have all three of these beans autowired into another class, like so:

@Controller
public class MyController {
    @Autowired
    private SomeDao someDao;

    @Autowired
    private Dep1 dep1;

    //...some methods
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.