Java how to do annotation configuration in spring

Java how to do annotation configuration in spring

In Spring, you can use annotations to configure your beans and their dependencies in the application context. Annotation-based configuration involves using annotations on your classes and methods to specify how they should be wired together in the application context.

Here's an example of how to use annotations to configure a bean in Spring:

@Configuration
public class AppConfig {

  @Bean
  public MyBean myBean() {
    return new MyBean();
  }
}
Source:w‮ww‬.lautturi.com

In the above example, the @Configuration annotation indicates that the AppConfig class is a configuration class that contains bean definitions. The @Bean annotation indicates that the myBean() method is a factory method that creates and returns a bean instance.

To use the bean in your application, you can inject it using the @Autowired annotation or the @Resource annotation.

Here's an example of how to use the @Autowired annotation to inject a bean in Spring:

@Component
public class MyComponent {

  @Autowired
  private MyBean myBean;

  // ...
}

In the above example, the @Component annotation indicates that the MyComponent class is a component class that can be managed by the Spring container. The @Autowired annotation injects the myBean field with the bean instance created by the myBean() factory method.

Alternatively, you can use the @Resource annotation to inject a bean by its name or by its type.

Here's an example of how to use the @Resource annotation to inject a bean by its name:

@Component
public class MyComponent {

  @Resource(name = "myBean")
  private MyBean myBean;

  // ...
}

In the above example, the @Resource annotation injects the myBean field.

Created Time:2017-11-03 22:21:05  Author:lautturi