Table of Contents

Create a class which you want to get as a bean, say a user and annotate it with @Configuration as:

@Configuration
public class User {
 @Value("codippa")//initialize the value of this field
 private String name;
 @Value("India")
 private String country;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }
 
}

 

[sc name=”AD1″ ]

Create a main class to get this bean. This class uses AnnotationConfigApplicationContext as ApplicationContext implementation:

public class Main {

 @SuppressWarnings("resource")
 public static void main(String[] args) {
  ApplicationContext context = new AnnotationConfigApplicationContext(User.class);
  User user = (User)context.getBean("user");
  System.out.println(user.getName());
  System.out.println(user.getCountry());
 }
}

This will print codippa and India.

[sc name=”AD2″ ]

There is another way of creating bean without XML configuration which is using @Component annotation. Refer Other ways of creating bean in Spring.

Let’s tweak in :

    1. You can also define packages where your beans reside instead of class names in AnnotationConfigApplicationContext as AnnotationConfigApplicationContext(“com.codippa”).
    2. @Configuration annotated class may also contain other bean definitions whose getter methods should be annotated with @Bean such as :
      @Configuration
      public class User {
        @Bean(name="extUser")
        public ExternalUser getUser() {
        return new ExternalUser();
       }
      }
      

      The bean with name “extUser” can be retrieved using getBean method of ApplicationContext as in above example.

[sc name=”Leaderboard-ad” ]
  1. @Value is used to provide value to class fields. The value may be given there only or may be fetched from an external property file using ${propertyName}.
  2. @Configurationis a class-level annotation. Applying it to some other level (such as a method or a field) will generate a compiler error The annotation @Configuration is disallowed for this location.

Liked this post ? Show your love by sharing it and don’t forget visiting again.

 

Categorized in:

Spring Boot,

Tagged in:

, , ,