我在一个项目中创建了一个配置类,定义了一个方法,然后尝试在另一个项目中导入一个配置,并调用了已定义的方法,但是我遇到了空指针异常。
我使用config类创建了bean,并尝试使用自动装配注释,但是对我来说不起作用
projectA:
@Configuration
public class DepositServiceConfig
{
@Bean
public DepositService depositService()
{
return new DepositService(depositModel.user_permisisons);
}
}
public class DepositService
{
private final DepositModel model;
public DepositService(depositModel model)
{
this.model = model;
}
public boolean hasRestrictions(string access)
{
return //
}
}
ProjectB:
@Import({
DepositServiceConfig.class,
})
public class DepositApp{
public static void main(String[] args)
{
SpringApplication.run(DepositApp.class, args);
}
}
@Component
public class ClientDeposits
{
@Autowired DepositServiceConfig depositConfig;
public boolean checkrestrcitions(){
if(depositConfig.depositService().hasRestrictions(access)) -- here i am getting null pointer exception.
}
如何使用config类中定义的depositService()bean而没有空指针异常
最佳答案
将@Component
添加到public class DepositService
解决了您的问题。您必须将DepositService指示为spring组件才能获取托管bean。