在Flink日常开发中,我们需要对业务Bean进行管理(也有可能从其他项目直接拿过来用),这个时候我们可以借助Spring来完成。
步骤总结如下:
一、引入依赖包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
二、创建Spring的配置文件
在resources目录下,创建applicationContext.xml文件
内容如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.xxx.rt.*" /> //注解扫描哪些包
<context:property-placeholder location="classpath:config.properties" /> //加载配置文件
</beans>
三、创建类来持有Spring的ApplicationContext
主要的目的是任何地方都能拿到ApplicationContext来获取想要的Bean
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getApplicationContext(){
return context;
}
public static <T> T getBean(Class<T> clazz){
if(context != null){
return context.getBean(clazz);
}
return null;
}
public static <T> T getBean(String name){
if(context != null){
return (T)context.getBean(name);
}
return null;
}
}
四、使用的main方法里初始化Spring
new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
五、获取Bean
Demo demo = ApplicationContextHolder.getBean(Demo.class);