使用@Configuration(spring无需xml配置文件创建对象的方法)
**优点:**无需applicationContext.xml文件
1.创建People对象
package com.tang.domain;
import org.springframework.beans.factory.annotation.Value;
public class People {
@Value("小明")
private String name;
@Value("22")
private Integer age;
public People() {
}
public People(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2.创建配置类
package com.tang.javaconfig;
import com.tang.domain.People;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JavaConfigration {
@Bean
public static People getPeople() {
return new People();
}
}
3.测试
import com.tang.domain.People;
import com.tang.javaconfig.JavaConfigration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfigration.class);
People people = ac.getBean("getPeople", People.class);
System.out.println(people);
}
}
4.结果
People{name='小明', age=22}
Process finished with exit code 0