Spring - Create bean in XML with reference to Java bean, and the other way around

Kims :

If I have a bean created in Java, with @Bean, how do I reference this bean in XML when creating a bean there? And if I have a bean created in XML, how do I reference this bean in Java when creating a bean there?

Santossh Kumhar :

Creating a bean in Java class is equivalent to creating the bean in the XML file. So if you want to refer a bean created in Java class in an XML file, simply use ref= beanName attribute to refer the bean and vice versa.

In the official documentation it says:

4.2.1. Declaring a bean

To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory. By default, the bean name will be that of the method name.

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }
}

The above is exactly equivalent to the following appConfig.xml:

<beans>
    <bean name="transferService" class="com.company.TransferServiceImpl"/>
</beans>

Both will result in a bean named transferService being available in the BeanFactory/ApplicationContext, bound to an object instance of type TransferServiceImpl:

And also you need to make sure you add

<bean class="org.springframework.config.java.process.ConfigurationPostProcessor"/> 

in your xml so your XML configuration and Java configuration has same bean definitions if they are declared in different contexts.

And if you want to include your traditional bean configuration from XML to Java configuration, then you need to Import the XML resource to that class as below:

@ImportResource({"classpath*:your-configuration.xml"})

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=139381&siteId=1
Recommended