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 :
-
- You can also define packages where your beans reside instead of class names in
AnnotationConfigApplicationContextasAnnotationConfigApplicationContext(“com.codippa”). @Configurationannotated class may also contain other bean definitions whose getter methods should be annotated with@Beansuch as :@Configuration public class User { @Bean(name="extUser") public ExternalUser getUser() { return new ExternalUser(); } }The bean with name “extUser” can be retrieved using
getBeanmethod ofApplicationContextas in above example.
- You can also define packages where your beans reside instead of class names in
- @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}. @Configurationis a class-level annotation. Applying it to some other level (such as a method or a field) will generate a compiler errorThe annotation @Configuration is disallowed for this location.
Liked this post ? Show your love by sharing it and don’t forget visiting again.
Leave a Comment