在使用spring框架中我们都知道,某个类如果使用了@Service、@Autowire 这种依赖注入的方式引用了其他对象,在另外一个类中,只有通过spring的IOC容重中获取这个类的实例时,那些被依赖的对象才能正确被初始化,否则那些被依赖的对象都是null。

所以就有一个问题,在普通类中如何获取spring ioc容器中的bean(spring 托管的bean)。

我们都知道,在spring中ApplicationContext这个上下文对象是获取bean的基础。在spring boot中,我们可以通过下面的方式来获取Bean。

@SpringBootApplication
@ComponentScan(basePackages = {"com.abc.efd.*"})
public class App {
  private static final Logger logger = LoggerFactory.getLogger(App2.class);
	
  public static void main(String[] args) {
    ConfigurableApplicationContext run = SpringApplication.run(App2.class, args);
		
    TestService instance = (TestService)run.getBean("testService");
	
    instance.process();
  }
}

当然,为了更加通用,我们可以创建一个工具:

public class SpringBeanUtils  {
    private static ApplicationContext applicationContext;
    public static void setApplicationContext(ApplicationContext applicationContext){
        SpringBeanUtils.applicationContext = applicationContext;
    }
}

然后再spring boot的main方法中设置:

@SpringBootApplication
public class WangMikeSpringApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(WangMikeSpringApplication.class, args);        
        SpringBeanUtils.setApplicationContext(applicationContext);
    }
}

接下来,我们再看一个多态的例子:

1)Test1Service、Test2Service类实现了ITestService接口:

//接口 ITestService.java
public interface ITestService {	
	void test() ;
}

//实现类Test1Service.java
@Service
public class Test1Service implements ITestService{
	@Override
	public void test() {
		System.out.println("test1 service...");
	}
}

//实现类Test2Service.java
@Service
public class Test2Service implements ITestService{

	@Override
	public void test() {
		System.out.println("test2 service...");
	}
}

2)主类:

@SpringBootApplication
@ComponentScan(basePackages = {"com.iqiyi.toutiao.zeus.woody.*"})
public class App{
	private static final Logger logger = LoggerFactory.getLogger(App.class);
	
	public static void main(String[] args) {
		ConfigurableApplicationContext run = SpringApplication.run(Test.class, args);
		
		ITestService t1Service = (ITestService)run.getBean("test1Service");
		t1Service.test();//test1 service...
		ITestService t2Service = (ITestService)run.getBean("test2Service");
		t2Service.test();//test2 service...
	}
}

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐