代码结构
1、新建maven项目,加入spring依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
2、新建DemoConfig
@Configuration
public class DemoConfig {
@Bean
public Person getPerson(){
return new Person(1,"123",12);
}
}
3、添加Person对象
//省略了get、set和无参构造函数
public class Person {
private Integer id;
private String name;
private Integer age;
}
4、main函数加载DemoConfig并获取
public class DemoApp {
public static void main(String[] args){
//ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
//Person person = (Person)applicationContext.getBean("person");
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(DemoConfig.class);
Person person = (Person)applicationContext.getBean("person");
System.out.println(person.toString());
}
}