spring注解注入map哪些注解可以注入对象

在filter里注入被注解的bean? - 知乎14被浏览9235分享邀请回答75 条评论分享收藏感谢收起关于Spring 注解注入对象问题 - ITeye问答
问题描述如下:
A 类是一个WS入口,调用B类的业务。 然后在B类里面注入service ,注入的service为空。
public class A{
private B b = new B();
public void test(){
b.method();
public class B{
private IEsbForEmpBusinessService esbForEmpBusinessS
在这个类里面的方法,调用esbForEmpBusinessService层的方法为空注入不进去。
@Service("esbForEmpBusinessServicesImpl")public class EsbForEmpBusinessServicesImpl implements IEsbForEmpBusinessService {
private IEsbForEmpBusinessDao esbBusinessD
public EsbToHrEmpInfo queryHrEmpInfo(String
emp_num) throws ServiceException {
EsbToHrEmpInfo ethe = esbBusinessDao.queryHrEmpInfo(emp_num);
@Override public void creatHrEmpInfo(EsbToHrEmpInfo hrempInfo) throws ServiceException {
esbBusinessDao.creatHrEmpInfo(hrempInfo);
@Override public void updateHrEmpInfo(EsbToHrEmpInfo hrempInfo,String emp_num) throws ServiceException {
esbBusinessDao.updateHrEmpInfo(hrempInfo,emp_num);
@Override public List&String& queryAreaCodeByNetCode(String netCode)
throws ServiceException {
return esbBusinessDao.queryAreaCodeByNetCode(netCode); }
问题: class B 里面的service对象注入不进来为null ,求解!!!!
采纳的答案
不能自己实例化bean,要通过sring获取。
@Service("esbForEmpBusinessServicesImpl")
public class EsbForEmpBusinessServiceImpl implements IEsbForEmpBusinessService {
&&& @Resource
&&& private IEsbForEmpBusinessDao esbBusinessD
&&& public EsbToHrEmpInfo queryHrEmpInfo(String emp_num) {
&&&&&&& System.out.println(emp_num);
&&&&&&& EsbToHrEmpInfo ethe = new EsbToHrEmpInfo();
&&&&&&&
@Service("serviceB")
public class B {
private IEsbForEmpBusinessService esbForEmpBusinessS
public void method() {
esbForEmpBusinessService.queryHrEmpInfo("111111");
@Service("serviceA")
public class A {
@Autowired
@Qualifier("serviceB")
public void test(){
b.method();
public static void main(String[] args) {
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("test.xml");
A a = (A) context.getBean("serviceA");
System.out.println(a);
public class A{
&& private B b = new B();
&& public void test(){
&&&&&& b.method();
}
直接B b = new B();是不行的,不会触发相关的注入
public class A{
&& @Resource(name="b")
&& private B
&& public void test(){
&&&&&& b.method();
看下你配置的注解扫描包路径有没有包括这个包。
@Service("esbForEmpBusinessServicesImpl") 里面的名字和esbForEmpBusinessService名字不同,改下看可以不。
已解决问题
未解决问题随笔 - 275
评论 - 2738通过上一篇 利用自定义Java注解实现资源注入 介绍的方法,我们实现了通过自定义注解完成了对DataSource资源的注入,但在实际应用中,我们通常不希望去显式的去声明这样的MyAnnotationBeanProcessor对象来帮助我们完成注入,而是希望通过Spring帮我们“悄悄地”完成。
继 利用自定义Java注解实现资源注入 里的代码(部分代码)不变,我们希望在测试类中以如下方法调用便可以实现资源的注入:
&&& import org.springframework.context.support.ClassPathXmlApplicationC&
&&& import com.annotation.MyS&
&&& public class SpringWiringTest {&
&&&&&&& public static void main(String args[]) {&
&&&&&&&&&&& ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("com/spring/applicationContext.xml");&
&&&&&&&&&&& MyService b = (MyService)ctx.getBean("myService"); // 通过Spring去管理bean,此时已完成了对标有DataSource注解的资源的注入&
&&&&&&&&&&& System.out.println(b.selectForObjectFromB("", null));&
&&&&&&&&&&& System.out.println(b.selectForObjectFromA("", null));&
&&&&&&& }&
注:MyService类实现在 利用自定义Java注解实现资源注入 中。
为了实现上面的目标,我们就不能使用MyAnnotationBeanProcessor.java类来实现对资源的注入了,我们必须实现一个能融入Spring的BeanProcessor类才行。
DataSourceBeanProcessor.java类实现BeanPostProcessor、PriorityOrdered接口:
&&& import java.lang.reflect.F&
&&& import org.springframework.beans.BeansE&
&&& import org.springframework.beans.factory.config.BeanPostP&
&&& import org.springframework.core.O&
&&& import org.springframework.core.PriorityO&
&&& public class DataSourceBeanProcessor implements BeanPostProcessor, PriorityOrdered {&
&&&&&&& @Override
&&&&&&& // 在这里完成资源注入&
&&&&&&& public Object postProcessAfterInitialization(Object bean, String beanName)&
&&&&&&&&&&& throws BeansException {&
&&&&&&&&&&& Class&?& cls = bean.getClass();&
&&&&&&&&&&& for (Field field : cls.getDeclaredFields()) {&
&&&&&&&&&&&&&&& if (field.isAnnotationPresent(DataSource.class)) {&
&&&&&&&&&&&&&&&&&&& DataSourceStaticWiring.wiring(bean, field);&
&&&&&&&&&&&&&&& }&
&&&&&&&&&&& }&
&&&&&&&&&&&&
&&&&&&& }&
&&&&&&& @Override
&&&&&&& public Object postProcessBeforeInitialization(Object bean, String beanName)&
&&&&&&&&&&& throws BeansException {&
&&&&&&&&&&&&
&&&&&&& }&
&&&&&&& @Override
&&&&&&& public int getOrder() {&
&&&&&&&&&&& return Ordered.LOWEST_PRECEDENCE;&
&&&&&&& }&
下面来看DataSourceStaticWiring的实现,与前一篇 里的DataSourceWiring.java类相比,改动点有以下三个:
1.不需要实现IFieldWiring接口
2.删除annotationClass方法
3.将wiring方法修改为static方法
具体代码如下:
&&& import java.lang.reflect.F&
&&& public class DataSourceStaticWiring {&
&&&&&&& public static void wiring(Object object, Field field) {&
&&&&&&&&&&& Object fieldObj = ReflectUtils.getFieldValue(object, field.getName());&
&&&&&&&&&&& if (fieldObj != null) {&
&&&&&&&&&&&&&&&&
&&&&&&&&&&& }&
&&&&&&&&&&& DataSource annotation = field.getAnnotation(DataSource.class);&
&&&&&&&&&&& String type = annotation.type();&
&&&&&&&&&&& String sqlMap = annotation.sqlMap();&
&&&&&&&&&&& // 这里可以用缓存来实现,不用每次都去创建新的SqlMapClient对象&
&&&&&&&&&&& SqlMapClient sqlMapImpl = new SqlMapClient(sqlMap, type);&
&&&&&&&&&&& ReflectUtils.setFieldValue(object, field.getName(), SqlMapClient.class, sqlMapImpl);&
&&&&&&& }&
注:SqlMapClient、ReflectUtils实现在上一篇 利用自定义Java注解实现资源注入 中。
代码已准备就绪,接下来是配置Spring: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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
&&&&&&& xmlns:context="http://www.springframework.org/schema/context"
&&&&&&& xsi:schemaLocation="http://www.springframework.org/schema/beans&&
&&&&&&&&&&&&&&&&&&&&&&&&&&& http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&
&&&&&&&&&&&&&&&&&&&&&&&&&&& http://www.springframework.org/schema/aop&&
&&&&&&&&&&&&&&&&&&&&&&&&&&& http://www.springframework.org/schema/aop/spring-aop-2.5.xsd&
&&&&&&&&&&&&&&&&&&&&&&&&&&& http://www.springframework.org/schema/tx&&
&&&&&&&&&&&&&&&&&&&&&&&&&&& http://www.springframework.org/schema/tx/spring-tx-2.5.xsd&
&&&&&&&&&&&&&&&&&&&&&&&&&&& http://www.springframework.org/schema/context&
&&&&&&&&&&&&&& http://www.springframework.org/schema/context/spring-context-2.5.xsd"&
&&&&&&& default-lazy-init="true"&
&&&&&&& &!-- 自定义的BeanProcessor --&
&&&&&&& &bean class="com.annotation.DataSourceBeanProcessor" /&
&&&&&&& &context:component-scan base-package="com.annotation" /&
&&&&&&& &!-- 测试用bean --&
&&&&&&& &bean id="myService" class="com.annotation.MyService" destroy-method="close"&
&&&&&&& &/bean&
&&& &/beans&
测试代码其实已经在前面列出来了。SpringWiringTest.java
&&& import org.springframework.context.support.ClassPathXmlApplicationC&
&&& import com.annotation.MyS&
&&& public class SpringWiringTest {&
&&&&&&& public static void main(String args[]) {&
&&&&&&&&&&& ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("com/spring/applicationContext.xml");&
&&&&&&&&&&& MyService b = (MyService)ctx.getBean("myService");&
&&&&&&&&&&& System.out.println(b.selectForObjectFromB("", null));&
&&&&&&&&&&& System.out.println(b.selectForObjectFromA("", null));&
&&&&&&& }&
执行结果:
SqlMapClient[sqlMap=com/annotation/sql-map-config-B.xml,type=B]
SqlMapClient[sqlMap=com/annotation/sql-map-config-A.xml,type=A]
由结果可见,我们利用Spring完成了对DataSource资源的注入了。
在这里如果还想扩展的话,就需要新建类假设为InParamBeanProcessor,实现BeanPostProcessor、PriorityOrdered接口,然后实现其中的方法,对资源进行注入,这里就是扩展Spring了,与本篇介绍的方法相同。
注:以上代码重在演示,其实这个需求可以在Spring中管理两个不同的SqlMapClient对象,然后通过Spring的自动注入实现。
celeskyking
浏览: 13977 次
来自: 北京
tiny.bear 写道tiny.bear 写道
tiny.bear 写道
kash_chen007 写道8错,
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'Spring依赖注入:注解注入总结 - 为程序员服务
为程序员服务
Spring依赖注入:注解注入总结
注解注入顾名思义就是通过注解来实现注入,Spring和注入相关的常见注解有Autowired、Resource、Qualifier、Service、Controller、Repository、Component。
Autowired是自动注入,自动从spring的上下文找到合适的bean来注入
Resource用来指定名称注入
Qualifier和Autowired配合使用,指定bean的名称
Service,Controller,Repository分别标记类是Service层类,Controller层类,数据存储层的类,spring扫描注解配置时,会标记这些类要生成bean。
Component是一种泛指,标记类是组件,spring扫描注解配置时,会标记这些类要生成bean。
上面的Autowired和Resource是用来修饰字段,构造函数,或者设置方法,并做注入的。而Service,Controller,Repository,Component则是用来修饰类,标记这些类要生成bean。
下面我们通过实例项目来看下spring注解注入的使用。
首先新建一个maven项目,并在pom中添加spring相关的依赖,如果不知道添加那些依赖,请参照上一篇文章。
然后新建CarDao类,给它添加@Repository注解,如下代码:
package cn.outofmemory.
import org.springframework.stereotype.R
@Repository
public class CarDao {
public void insertCar(String car) {
String insertMsg = String.format(&inserting car %s&, car);
System.out.println(insertMsg);
新建CarService类,并给该类标注@Service注解,在这个类中定义CarDao的字段,并通过Autowired来修饰此字段,这样上面定义的CarDao类的实例就会自动注入到CarService的实例中了。
package cn.outofmemory.
import org.springframework.beans.factory.annotation.A
import org.springframework.stereotype.S
public class CarService {
@Autowired
private CarDao carD
public void addCar(String car) {
this.carDao.insertCar(car);
注意:Autowired注解有一个可以为空的属性required,可以用来指定字段是否是必须的,如果是必需的,则在找不到合适的实例注入时会抛出异常。
下面我们在App.java中使用上面测试下注解注入:
package cn.outofmemory.
import org.springframework.context.ApplicationC
import org.springframework.context.annotation.AnnotationConfigApplicationC
* Hello world!
public class App
public static void main( String[] args )
ApplicationContext appContext = new AnnotationConfigApplicationContext(&cn.outofmemory.helloannotation&);
CarService service = appContext.getBean(CarService.class);
service.addCar(&宝马&);
在上面的main方法中首先我们初始化了appContext,他是AnnotationConfigApplicationContext,它的构造函数接受一个package的名称,来限定要扫描的package。然后就可以通过appContext的getBean方法获得CarService的实例了。
上面的例子非常简单,单纯的使用AnnotationConfigApplicationContext就可以了,但是在实际项目中情况往往没有这么简单,还是需要spring配置文件的。在spring配置文件中也可以通过下面的配置让spring自动扫描注解配置。
&!-- bean annotation driven --&
&context:annotation-config /&
&context:component-scan base-package=&cn.outofmemory.helloannotation& &
&/context:component-scan&
下面我们看下混合使用spring配置和注解的例子,首先在项目中添加source folder,src/main/resources,并添加spring.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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd &&
&!-- bean annotation driven --&
&context:annotation-config /&
&context:component-scan base-package=&cn.outofmemory.helloannotation& &
&/context:component-scan&
&bean id=&sqliteCarDao& class=&cn.outofmemory.helloannotation.CarDao& &
&constructor-arg name=&driver& value=&sqlite&/&
在上面的配置文件中,我们通过context:annotation-config和context:component-sacn节点来指定要扫描注解注入,然后又定义了一个id为sqliteCarDao的bean,它的构造函数的driver值为sqlite。
我们修改下App.java使用xml配置文件,再运行下App看下会怎样。
package cn.outofmemory.
import org.springframework.context.ApplicationC
import org.springframework.context.annotation.AnnotationConfigApplicationC
import org.springframework.context.support.ClassPathXmlApplicationC
* Hello world!
public class App
public static void main( String[] args )
//ApplicationContext appContext = new AnnotationConfigApplicationContext(&cn.outofmemory.helloannotation&);
ApplicationContext appContext = new ClassPathXmlApplicationContext(&/spring.xml&);
CarService service = appContext.getBean(CarService.class);
service.addCar(&宝马&);
运行程序发现输出为:inserting car 宝马 into mysql,显然CarService自动注入的CarDao使用了默认构造函数构造的实例。是否可以通过注解指定使用spring.xml中配置的sqliteCarDao呢?
我们可以修改下CarService类,通过Qualifier注解来指定要使用的bean的名字。
如下,在指定Autowired注解时,同时指定Qualifier注解指定bean的名字
@Autowired
@Qualifier(&sqliteCarDao&)
private CarDao carD
重新运行下App.java 这次输出的是inserting car 宝马 into sqlite,这次使用了spring.xml中配置的bean了。
在文中开头我们还提到了Resouce注解,这个注解可以指定名字注入,我们再次修改下CarService类:
@Resource(name=&sqliteCarDao&)
private CarDao carD
javax.annotation.Resource注解实现的效果和@Autowired+@Qualifier的效果是一样的。
您可能的代码
相关聚客文章
荣誉:2088
相关专栏文章

我要回帖

更多关于 spring注解注入属性值 的文章

 

随机推荐