欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

【SpringBoot学习笔记】使用JavaConfig配置容器

时间:2023-08-06

首先创建所需要的类:

package com.blushyes.vo;public class Student { private String name; private Integer age; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "Student{" + "name='" + name + ''' + ", age=" + age + ", sex='" + sex + ''' + '}'; }}

然后创建SpringConfig类用于配置容器:

package com.blushyes.config;import com.blushyes.vo.Student;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class SpringConfig { @Bean public Student createStudent(){ Student student = new Student(); student.setName("张三"); student.setAge(19); student.setSex("男"); return student; }}

@Configuration注解的意思是该类是用于配置容器的类。
@Bean可以指定id如@Bean(id=“myStudent”),默认为方法名。

从容器中提取对象:

ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);//根据JavaConfig创建容器Student student = (Student) context.getBean("createStudent");//提取对象System.out.println(student);

输出:

Student{name=‘张三’, age=19, sex=‘男’}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。