I am beginner to spring. I have gone through some online tutorials and written a simple program, but I couldn't understand the worth. When we use spring.xml file and we create object with getBean method. But, in case of annotations I am creating the object using new, which I think is not right. Please see below the code and let me know if the procedure i have followed is problematic or not.
Hello.java:
package bean;
import org.springframework.stereotype.Component;
@Component
public class Hello {
String gender;
public void print(){
System.out.println("Hello world "+gender);
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
AppConfig.java:
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import bean.Hello;
@Configuration
public class AppConfig {
@Bean(name="h")
public Hello getHello(){
Hello h= new Hello();
h.setGender("male");
return h;
}
}
Driver.java:
package client;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import bean.Hello;
import config.AppConfig;
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ct=new AnnotationConfigApplicationContext(AppConfig.class);
Hello h=ct.getBean("h",Hello.class);
h.print();
}
}
As you can see in AppConfig.java, I am creating the object of my class using
Hello h= new Hello();
This looks problematic. If i have to create object by myself, then why do we need spring. Please suggest what I am doing wrong here.
Springobject could be configured from a xml file. Very useful if you want to change values e.g. for a DB Connection or some other configuration ObjectHello h=ct.getBean("h",Hello.class);- what is wrong with this? Also search for bean injectionnew- see autowired or use the same method as per yourmain