How to configure Spring Application using java based configuration
Spring Application Require a Config class to define the bean definition .
The config class annotated with @Configuration annotation and @Bean annotation used for bean describe bean definition.
AnnotationConfigApplicationContext class an implementation of ApplicationContext is used to
initialization of Spring application config using spring configuration class
SpringConfig .java
package in.jk.javaconfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig {
@Bean(name = "user")
public User getUser() {
return new User();
}
}
User .java
package in.jk.javaconfig;
public class User {
private int userId;
private String userName;
private String password;
private String email;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName + ", password=" + password + ", email=" + email
+ "]";
}
}
SpringApplication .java
package in.jk.javaconfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringApplication {
public static void main(String[] args) {
ApplicationContext applicationContext = null;
applicationContext =new AnnotationConfigApplicationContext(SpringConfig.class);
System.out.println("Spring Config initialize :: ");
User user = (User) applicationContext.getBean("user");
user.setUserId(1);
user.setUserName("jk");
user.setEmail("jk@gmail.com");
user.setPassword("jk123");
System.out.println(user);
}
}
Here is output in console -
Spring Config initialize ::
User [userId=1, userName=jk, password=jk123, email=jk@gmail.com]
No comments:
Post a Comment