Spring in @ImportResource

Brief introduction

This comment is very simple, is to import the spring xml configuration file

Direct view spring official document:

In applications where @Configuration classes are the primary mechanism for configuring the container, it will still likely be necessary to use at least some XML. In these scenarios, simply use @ImportResource and define only as much XML as is needed. Doing so achieves a "Java-centric" approach to configuring the container and keeps XML to a bare minimum.

When we use the java class configuration, such as springboot project, it is recommended to use java class configuration, in theory, we can completely eliminate the xml configuration file, but sometimes we need to import spring xml configuration file, you need to use this comment

For example:

The first is our java class configuration

@Configuration
@ImportResource("classpath:/com/acme/properties-config.xml")
public class AppConfig {

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource dataSource() {
        return new DriverManagerDataSource(url, username, password);
    }
}
properties-config.xml
<beans>
    <context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>
</beans>

jdbc.properties

jdbc.properties
jdbc.url=jdbc:hsqldb:hsql://localhost/xdb
jdbc.username=sa
jdbc.password=

Running the test method:

public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
    TransferService transferService = ctx.getBean(TransferService.class);
    // ...结果略
}

Explanation

These are the spring official documentation for instructions and examples of the annotation, relatively simple, not repeat them.

Guess you like

Origin www.cnblogs.com/heliusKing/p/11487503.html