关于Spring 注解注入对象问题

问题描述如下:

A 类是一个WS入口,调用B类的业务。 然后在B类里面注入service ,注入的service为空。

public class A{

   private B b = new B();

   public void test(){

       b.method();

}

}

 

public class B{

    @Resource
     private IEsbForEmpBusinessService esbForEmpBusinessService;

 

    在这个类里面的方法,调用esbForEmpBusinessService层的方法为空注入不进去。

}

 

@Service("esbForEmpBusinessServicesImpl")
public class EsbForEmpBusinessServicesImpl implements IEsbForEmpBusinessService {
     @Resource
     private IEsbForEmpBusinessDao esbBusinessDao ;
 
 
   @Override
   public EsbToHrEmpInfo queryHrEmpInfo(String  emp_num) throws ServiceException {
    EsbToHrEmpInfo ethe = esbBusinessDao.queryHrEmpInfo(emp_num);
    return ethe ;

   }

 @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 ,求解!!!!


尚方宝剑之说
浏览 649回答 4
4回答

白板的微信

不能自己实例化bean,要通过sring获取。@Service("esbForEmpBusinessServicesImpl")public class EsbForEmpBusinessServiceImpl implements IEsbForEmpBusinessService {@Resource private&nbsp;IEsbForEmpBusinessDao&nbsp;esbBusinessDao; public&nbsp;EsbToHrEmpInfo&nbsp;queryHrEmpInfo(String&nbsp;emp_num)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;System.out.println(emp_num); &nbsp;&nbsp;&nbsp;&nbsp;EsbToHrEmpInfo&nbsp;ethe&nbsp;=&nbsp;new&nbsp;EsbToHrEmpInfo(); &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;ethe; }}@Service("serviceB")public class B {@Resource private&nbsp;IEsbForEmpBusinessService&nbsp;esbForEmpBusinessService; public&nbsp;void&nbsp;method()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;esbForEmpBusinessService.queryHrEmpInfo("111111"); }}@Service("serviceA")public class A {@Autowired @Qualifier("serviceB") private&nbsp;B&nbsp;b; public&nbsp;void&nbsp;test(){ &nbsp;&nbsp;&nbsp;&nbsp;b.method();}public static void main(String[] args) {&nbsp;&nbsp;&nbsp;&nbsp;FileSystemXmlApplicationContext&nbsp;context&nbsp;=&nbsp;new&nbsp;FileSystemXmlApplicationContext("test.xml"); &nbsp;&nbsp;&nbsp;&nbsp;A&nbsp;a&nbsp;=&nbsp;(A)&nbsp;context.getBean("serviceA"); &nbsp;&nbsp;&nbsp;&nbsp;System.out.println(a); &nbsp;&nbsp;&nbsp;&nbsp;a.test(); }

吃鸡游戏

@Service("esbForEmpBusinessServicesImpl") 里面的名字和esbForEmpBusinessService名字不同,改下看可以不。@Resource(name="esbForEmpBusinessServicesImpl") private IEsbForEmpBusinessService esbForEmpBusinessService;

郎朗坤

看下你配置的注解扫描包路径有没有包括这个包。

慕仙森

public class A{private B b = new B();public void test(){&nbsp;&nbsp;&nbsp;b.method();}}直接B b = new B();是不行的,不会触发相关的注入public class A{@Resource(name="b")private B b ;public void test(){&nbsp;&nbsp;&nbsp;b.method();}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java