Spring @Autowire
字段为null
,即使它在其他类中也可以正常工作。
public class SendRunner implements Runnable {
private String senderAddress;
@Autowired
private SubscriberService subscriberService;
public SendRunner(String senderAddress) {
this.senderAddress = senderAddress;
}
@Override
public void run() {
sendRequest();
}
private void sendRequest() {
try {
HashMap<String, String> dataMap = new HashMap<>();
dataMap.put("subscriberId", senderAddress);
HttpEntity<?> entity = new HttpEntity<Object>(dataMap, httpHeaders);
Subscriber subscriber = subscriberService.getSubscriberByMsisdn(senderAddress);
} catch (Exception e) {
logger.error("Error occurred while trying to send api request", e);
}
}
该类也作为调度程序servlet中的bean管理:
<bean id="SendRunner" class="sms.dating.messenger.connector.SendRunner">
</bean>
在这里,我得到subscriberService
的空指针异常。这可能是什么原因?预先感谢。
答案 0 :(得分:0)
能否请您用@Component或@Service注释SendRunner类,并将SendRunner包包含在componentscanpackage中
答案 1 :(得分:0)
您的bean不在Spring Managed上下文中,可能是以下原因。
软件包sms.dating.messenger.connector不在组件扫描中。
您将通过使用new创建一个对象来退出Spring上下文(请参见下文), 这样,您将不会获得自动装配的字段。
SendRunner sendRunner = new SendRunner () ,
sendRunner.sendRequest();
只需检查我的实施方式即可。希望这会有所帮助。
@RestController
public class RestRequest {
@Autowired
SendRunner sendRunner;
@RequestMapping("/api")
public void Uri() {
sendRunner.start();
}
}
SendRunner类
@Service
public class SendRunner extends Thread{
@Autowired
private SubscriberService subscriberService;
@Override
public void run() {
SendRequest();
}
private void SendRequest() {
System.out.println("Object is " + subscriberService);
String senderAddress = "address";
subscriberService.getSubscriberByMsisdn(senderAddress);
}
}
下面是我点击REST API时打印的日志。
对象是com.example.demo.SubscriberService@40f33492
答案 2 :(得分:0)
请尝试以下代码段
@Configuration
public class Someclass{
@Autowired
private SubscriberService subscriberService;
Thread subscriberThread = new Thread() {
@Override
public void run() {
try {
HashMap<String, String> dataMap = new HashMap<>();
dataMap.put("subscriberId", senderAddress);
HttpEntity<?> entity = new HttpEntity<Object>(dataMap, httpHeaders);
Subscriber subscriber = subscriberService.getSubscriberByMsisdn(senderAddress);
} catch (Exception e) {
logger.error("Error occurred while trying to send api request", e);
}
}
};
}