Spring 中bean的两种定义方式:配置文件和注解
在spring中,有两种方式可以定义bean,一种是比较老的配置文件的形式。另一种就是Java 类的配置方式
先列举一下本次需要用到的类:com.atguigu.bean.Persion.该类中,需要有两个属性:name,age。
每个属性都有get set 方法,以及两个构造函数。一个带参数的构造函数和一个无参构造函数,以及一个toString方法。
第一种:配置文件beans.xml
在maven项目中,在resource 目录下,新建一个配置文件beans.xml。主要内容如下:
id 表示这个bean的ID
class,表示这个bean对应的类
property表示类中对应的属性。
在main 函数中获取bean的方式:
// //通过xml 配置文件的形式获取bean开始
// ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");
// Person bean=(Person) applicationContext.getBean("person");
// System.out.print(bean);
// //通过xml 配置文件的形式获取bean结束
第二种:注解方式,Java类
创建一个配置类MainConfig,通过注解Configuration告诉spring 这是一个配置类。然后通过@Bean("person")表示,这是一个bean,其中bean的id是person
在main函数中,获取bean的方式: