通过容器拿到bean

通过容器拿到bean,第1张

通过容器拿到bean

通过Spring容器拿到bean,不通过依赖注入,SpringBoot框架

1.自定义bean

package com.baosight.jhy.pc.cs.domain;

public class Teacher {

    private String name;

    private String address;

    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

2.注册bean到Spring容器

package com.baosight.jhy.pc.cs.excel;

import com.baosight.jhy.pc.cs.domain.Teacher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ExcelConfig {


    @Bean
    public Teacher teacher() {
        Teacher teacher = new Teacher();
        teacher.setName("无双剑姬");
        teacher.setAddress("恕瑞玛");
        teacher.setAge(6300);
        return teacher;

    }


}

3.Spring容器获取

package com.baosight.jhy.pc.cs.excel;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


@Component
public class SpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException {
        SpringContextUtils.context = context;
    }

    public static ApplicationContext getContext() {
        return context;
    }

}

4.获取bean

        Teacher bean = SpringContextUtils.getContext().getBean(Teacher.class);
        bean.getName();

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

原文地址: https://outofmemory.cn/zaji/5436681.html

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

发表评论

登录后才能评论

评论列表(0条)

保存