025. Configuration - dkkahm/study-springfamework5 GitHub Wiki

Java Configuration

@COnfiguration
public class ChuckConfiguration {

Bean

  • Return type matter, not function name
    @Bean
    public ChuckNorrisQuotes chuckNorrisQuotes() {
        return new ChuckNorrisQuotes();
    }
  • Using Bean
   @Autowired
   private ChuckNorrisQuotes chuckNorrisQuotes;

XML Configuration

  • XML config file position
    • resources/cuck-config.xm
  • Loading configuration
@SpringBootApplication
@ImportResource("classpath:chuck-config.xml")
public class JokeApplication {

Spring Factory Bean

  • Factory
public class GreetingServiceFactory {
    private GreetingRepositsory repository;

    public GreetingServiceFactory (GreetingRepositsory repository) {
        this.repository = repository;
    }

    public GreetingService createGreetingService(String lang) {
        switch(lang) {
            case "en":
                return new PrimaryGreetingService(...);
            case "de":
                return new PrimaryGermanGreetingService(...);
        ....
    }
  • Configuration
@Configuration
public class GreetingSeericeConfig {
    @Bean
    GreetingSericeFactory greetingSericeFactory(GreetingRepositsory repository) {
        return new GreetingServiceFactory(repository);
    }

    @Bean
    @Primary
    @Profile({"default", "en"})
    GreetingService primaryGreetingService(GreetingServiceFactory greetingServiceFactory) {
        return greetingServiceFactory.createGreetingService("en");
    }

    @Bean
    @Primary
    @Profile("es")
    GreetingService primarySpanishGreetingService(GreetingServiceFactory greetingServiceFactory) {
        return greetingServiceFactory.createGreetingService("es");
    }

    ....

Spring Boot Auto Configuration Report

  • application.properties
    • debug=true
    • logging.level.root=debug
  • command line arguments
1. add to build.gradle
bootRun {
	systemProperties = System.properties
}

2. run with -Ddebug=true
  gradlew bootRun -Ddebug=true

Spring Bean Scope

  • Singleton
    • default
  • Prototype
    • A new instance is created each time the bean is requested
  • Request
    • A single instance per http request
  • Session
    • A single instance per http session
  • Applicaton
    • bean is scoped to the lifecyle of a ServletContext
  • Websocket
    • Scopes a single bean definition to the lifecyle of a WebSocket
  • Global-session
    • A single instance per global session
    • Typically Only used in a Portlet context
  • In Java Configuration
    • Use @Scope annotation
  • In XML Configuration
    • Use scope attribute