文章目录
目录
前言
一、实现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();
}
}
控制台输出:
public interface UserService {
void user();
}
2.Student子接口
public interface StudentService extends UserService {
void student();
}



