问题
之前通过spring boot的注入是通过 @Autowried 进行的,但是如果想要配置bean中的参数或者对象就比较不方便。可以用之前spring的XML方式注入bean。
场景
在一个bean中注入一个map, map的类型是<String,Object>
bean
需要注入的bean
@Service
public class DruidEngineService implements IEngineService {
DruidDaoImpl("192.168.7.56:8085");
private Map<String,DruidDaoImpl> druidDaoImplMap;
public Map<String, DruidDaoImpl> getDruidDaoImplMap() {
return druidDaoImplMap;
}
public void setDruidDaoImplMap(Map<String,DruidDaoImpl> druidDaoImplMap) {
this.druidDaoImplMap = druidDaoImplMap;
}
....
}
在map中需要注入的bean
@Repository
public class DruidDaoImpl implements IStorageDao{
private String routerUrl;
public String getRouterUrl() {
return routerUrl;
}
public void setRouterUrl(String routerUrl) {
this.routerUrl = routerUrl;
}
....
}
注入这个bean的类
@Component
public class MESRestfulServiceParser {
private static final Logger logger = LoggerFactory.getLogger(MESRestfulServiceParser.class);
@Autowired
private SparkEngineService sparkService;
@Autowired
@Qualifier("druidEngineService")
private DruidEngineService druidService;
...
}
note. @Component 这种标注一定要加,要不然spring boot 不认识。
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="druidEngineService" class="com.mafengwo.mesc.mesdataapi.dispatcher.DruidEngineService">
<property name="druidDaoImplMap" >
<map>
<entry key="default" value-ref="dataDruid"/>
<entry key="web_proxy_log" value-ref="operationDruid"/>
</map>
</property>
</bean>
<bean id="dataDruid" class="com.mafengwo.mesc.mesdataapi.dao.Impl.DruidDaoImpl">
<property name="routerUrl" value="192.168.7.56:8085"/>
</bean>
<bean id="operationDruid" class="com.mafengwo.mesc.mesdataapi.dao.Impl.DruidDaoImpl">
<property name="routerUrl" value="192.168.10.22:8082"/>
</bean>
</beans>
配置类
spring boot还需要一个配置类
@Configuration
@ImportResource(locations = {"classpath:druid-beans.xml"})
public class BeanConfig {
}
指明地址就好
网友评论