我有一个配置类,它为我的应用程序创建bean。我看到虽然我在创建适配器bean时设置了bean属性,但是在我的控制器类中,这些属性在某种程度上被清除并设置为null。经过2个小时的调试,我正在画一个空白。请指点。
@RequiredArgsConstructor//lombok annotation to generate the constructor.
public class MyAdapter {//Trying to create a bean of this type
@NonNull private final MyPropertyObj prop;
@NonNull private final Integer timeout;
}
@Configuration
@Profile("!test")
class MyConfigClass{
@Bean
public MyAdapter adapter(){
MyPropertyObj prop= new MyPropertyObj();
return new MyAdapter(prop, 10);//Here I am setting prop and 10, but when I check auto wired adapter they are null.
}
}
public class MyController {
@Autowired private MyAdapter adapter;
//adapter gets injected, but adapter.prop and the adapter.timeout are null.
}
答案 0 :(得分:0)
您应该使用
为控制器添加注释@Controller
注释
答案 1 :(得分:0)
我有类似的问题:
@Controller
public class MyController {
@Autowired
private LogService logService;
@RequestMapping(value = "/logs/view", method = RequestMethod.POST)
private String getLogList(SearchLogBean searcher, BindingResult bindingResult, Model model) {
List<LogActions> logs = logService.findAllByActionDateBetween(searcher.getFrom(), searcher.getTo());
model.addAttribute("items", logs);
return "logPage";
}
}
在其他包装中,我可以提供服务
@Service
public class LogServiceImpl implements LogService {
@Override
public List<LogActions> findAllByActionDateBetween(Date from, Date to) {
...
}
在控制器中,getLogList autowired logService == null,在测试中,它已成功自动装配。 错误是控制器方法为 PRIVATE 。 此方法必须公开。 (Spring将绑定到带URL注释的@RequestMapping私有控制器方法-https://github.com/spring-projects/spring-framework/issues/21417;但是从私有方法中,我们不能使用控制器私有字段(不仅自动装配,而且例如私有Integer some_value = 12;在这种情况下将为null方法))