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

【SpringBoot学习笔记】使用JavaConfig配置容器,第1张

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

首先创建所需要的类:

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;

@Configuration
public 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=‘男’}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5722348.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存