[Spring Boot] 07 @PropertySource and @ ImportResource

Keywords: Spring SpringBoot xml encoding

@PropertySource and @ ImportResource

@PropertySource: load the specified configuration file

@PropertySource(value = {"classpath:person.properties"})
@Component
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;

@Import resource: import the Spring configuration file to make the content in the configuration file effective

There is no Spring configuration file in Spring Boot, and the configuration file we wrote ourselves cannot be recognized automatically.

If you want Spring's configuration file to load effectively, mark @ ImportResource on a configuration class

package com.memory.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

// Import Spring's configuration file for it to take effect
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBoot02ConfigApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot02ConfigApplication.class, args);
    }
}

Don't write Spring's configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="helloService" class="com.memory.springboot.service.HelloService"></bean>
</beans>

How SpringBoot recommends adding components to containers: how to recommend usage annotations

1. Configuration class - Spring configuration file

2. Use @ Bean to add components to the container

package com.memory.springboot.config;

import com.memory.springboot.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Configuration: Indicates that the current class is a configuration class, which is to replace the previous Spring configuration file.
 *
 * Add components with < bean > < bean > tag in configuration file
 */
@Configuration
public class MyAppConfig {

    // Add the return value of the method to the container: the default Id of this component in the container is the method name
    @Bean
    public HelloService helloService(){
        System.out.println("Configuration class @Bean Add components to the container");
        return new HelloService();
    }
}

Posted by mk1200 on Wed, 30 Oct 2019 22:51:46 -0700