Development

스프링 부팅에서 @Configuration 주석을 사용하는 방법.

sonpro 2023. 3. 14. 08:10
반응형

@Configuration

How to Use @Configuration Annotation in Spring Boot

Spring Boot is a popular framework for building Java applications. It provides a lot of features that make it easy to develop and deploy applications. One of the key features of Spring Boot is the @Configuration annotation. In this blog post, we will explore how to use the @Configuration annotation in Spring Boot.

Summary

The @Configuration annotation is used in Spring Boot to define configuration classes. These classes contain methods that define beans, which are objects that Spring manages. By using the @Configuration annotation, you can define beans in a modular and reusable way. This makes it easy to configure your application and manage dependencies.

Defining a Configuration Class

To define a configuration class in Spring Boot, you simply need to annotate a class with @Configuration. For example:

@Configuration
public class MyConfiguration {
    // Define beans here
}

Once you have defined a configuration class, you can start defining beans.

Defining Beans

To define a bean in Spring Boot, you need to annotate a method with @Bean. For example:

@Configuration
public class MyConfiguration {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

In this example, we have defined a bean called "myBean". The method returns an instance of the MyBean class, which is then managed by Spring.

Injecting Beans

Once you have defined a bean, you can inject it into other classes using the @Autowired annotation. For example:

@Service
public class MyService {
    @Autowired
    private MyBean myBean;
}

In this example, we have injected the "myBean" bean into the MyService class. Spring will automatically wire up the dependency for us.

Using Profiles

Spring Boot provides support for profiles, which allow you to define different configurations for different environments. To define a profile, you can use the @Profile annotation. For example:

@Configuration
@Profile("dev")
public class DevConfiguration {
    @Bean
    public MyBean myBean() {
        return new DevMyBean();
    }
}

@Configuration
@Profile("prod")
public class ProdConfiguration {
    @Bean
    public MyBean myBean() {
        return new ProdMyBean();
    }
}

In this example, we have defined two configuration classes, one for the "dev" profile and one for the "prod" profile. Each configuration class defines a different implementation of the MyBean class.

Conclusion

The @Configuration annotation is a powerful feature of Spring Boot that allows you to define beans in a modular and reusable way. By using the @Configuration annotation, you can easily configure your application and manage dependencies. We hope this blog post has helped you understand how to use the @Configuration annotation in Spring Boot. Happy coding!

반응형