栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 实现根据bean的name获取对应的实体类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot 实现根据bean的name获取对应的实体类

 文章目录

目录

前言

一、实现ApplicationContextAware接口

二、其他测试类接口

1.父接口

2.Student子接口

2.1Student子接口实现类

3.Teacher子接口

3.1Teacher子接口实现类

4.测试使用

控制台输出:

总结


前言

项目中需要使用bean的不同name获取对应的不同Bean对象需求。

一、实现ApplicationContextAware接口

 根据ApplicationContext的getBean方法实现主要功能

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


@Component
public class ApplicationContextGetBeanHelper implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static Object getBean(String className) throws BeansException, IllegalArgumentException {
        if (className == null || className.length() <= 0) {
            throw new IllegalArgumentException("className为空");
        }

        String beanName = null;
        if (className.length() > 1) {
            beanName = className.substring(0, 1).toLowerCase() + className.substring(1);
        } else {
            beanName = className.toLowerCase();
        }
        return applicationContext != null ? applicationContext.getBean(beanName) : null;
    }
}

二、其他测试类接口

1.父接口
public interface UserService {
    void user();
}
2.Student子接口
public interface StudentService extends UserService {
    void student();
}

2.1Student子接口实现类
@Service("studentService")
public class StudentServiceImpl implements StudentService {
    @Override
    public void student() {
        System.out.println("student");
    }

    @Override
    public void user() {
        System.out.println("student==user");
    }
}
3.Teacher子接口
public interface TeacherService extends UserService {
    void  teacher();
}
3.1Teacher子接口实现类
@Service("teacherService")
public class TeacherServiceImpl implements TeacherService {
    @Override
    public void teacher() {
        System.out.println("teacher");
    }

    @Override
    public void user() {
        System.out.println("teacher===user");
    }
}
4.测试使用
@SpringBootTest
public class UserServiceTest {
    @Test
    public void user() {
        UserService user = (UserService) ApplicationContextGetBeanHelper.getBean("studentService");
        user.user();
    }
}

控制台输出:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/713493.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号