How to create bean without XML configuration in Spring / How to create bean in Spring using Annotations

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.

  3. [sc name=”Leaderboard-ad” ]
  4. @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}.
  5. @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.

 

0

Leave a Reply

Mark Your Impression

  Subscribe  
Notify of
Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.