Spring中Bean是一个非常重要的概念,在SSM的流行年代,一般通过XML文件来配置Bean,随着SpringBoot框架的流行,注解(Annotation)的方式因为配置方便,简洁,自动化也逐渐深入人心。但是从功能上来说,两者的功能并没有太大的区别,本章主要是展示两者的创建的实例,以及常见的注解展示。
使用XML配置SpringBean的方式
定义一个POJO对象如下
public class Student {private String name;private Integer age;private List<String> lessonList;// 篇幅问题,请手动补上sette & getter & toString 方法}
在resource是目录下定义
bean.xml文件
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 手动的注入Bean对象--><bean id="student" class="com.zhoutao123.spring.annotation.bean.Student"><property name="name" value="燕归来兮"/><property name="age" value="18"/><property name="lessonList"><list><value type="java.lang.String">语文</value><value type="java.lang.String">数学</value></list></property></bean></beans>
- 在类目录创建main方法
public static void main(String[] args) {ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");Student bean = context.getBean(Student.class);System.out.println(bean);}
- 执行结果
Student{name='燕归来兮', age=18, lessonList=语文,数学}
使用Annotation 注解的方式实现
定义配置文件
MainConfig@Configurationpublic class MainConfig {@Bean("测试Bean")public Student student() {Student student = new Student();student.setAge(18);student.setLessonList(Arrays.asList("数学", "英语"));student.setName("燕归来兮");return student;}}
在类目录下创建
main方法public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);// 从IOC容器中获取到Bean实例对象Student bean = context.getBean(Student.class);System.out.println(bean);// 输出Bean的名称,,如果在@Bean注解中,指定的话,就是Bean的指定值,否则为定义Bean的方法名,System.out.println("BeanName = " + String.join(",", context.getBeanNamesForType(Student.class)));}
执行结果
Student{name='燕归来兮', age=18, lessonList=数学,英语}BeanName = 测试Bean
