1.配置类
package com.visy.configure;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Component
public class SpringBeanContext implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
context = ctx;
}
public <T> T getBean(Class<T> clazz){
return Objects.isNull(context) ? null : context.getBean(clazz);
}
public <T> T getBean(String name, Class<T> clazz){
return Objects.isNull(context) ? null : context.getBean(name, clazz);
}
public Object getBean(String name){
return Objects.isNull(context) ? null : context.getBean(name);
}
public <T> T getBean(Class<T> clazz, Object ...args){
return Objects.isNull(context) ? null : context.getBean(clazz, args);
}
public Object getBean(String name, Object ...args){
return Objects.isNull(context) ? null : context.getBean(name, args);
}
}
2.服务接口
package com.visy.service;
public interface UserService {
void addUser(String userName);
}
package com.visy.service;
public interface TestService {
void test();
void test2();
}
3.服务接口实现
package com.visy.service.impl;
import com.visy.service.UserService;
import org.springframework.stereotype.Service;
@Service("userService1")
public class UserServiceImpl1 implements UserService {
@Override
public void addUser(String userName) {
System.out.println(this.getClass().getSimpleName()+" addUser : "+ userName);
}
}
package com.visy.service.impl;
import com.visy.service.UserService;
import org.springframework.stereotype.Service;
@Service("userService2")
public class UserServiceImpl2 implements UserService {
@Override
public void addUser(String userName) {
System.out.println(this.getClass().getSimpleName()+" addUser : "+ userName);
}
}
package com.visy.service.impl;
import com.visy.configure.SpringBeanContext;
import com.visy.service.TestService;
import com.visy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TestServiceImpl implements TestService {
@Autowired
private SpringBeanContext springBeanContext;
@Override
public void test() {
TestService self = springBeanContext.getBean(TestService.class);
self.test2();
}
@Override
public void test2() {
UserService userService1 = springBeanContext.getBean("userService1", UserService.class);
UserService userService2 = springBeanContext.getBean("userService2", UserService.class);
userService1.addUser("张三");
userService2.addUser("李四");
}
}