【问题标题】:Why does my Autowired bean has null properties为什么我的 Autowired bean 有空属性
【发布时间】:2019-08-03 12:38:53
【问题描述】:

我有一个为我的应用程序创建 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.
}

【问题讨论】:

  • 你的类myAdapter的构造函数在哪里?
  • @Augustas 我看了那个问题。这个问题是关于手动创建一个新对象并期望它内部的属性是自动连接的。我想要做的是不同的。我在实例化过程中创建的 bean 以某种方式改变了状态并清除了它的属性。
  • @Jens RequiredArgsConstructor 生成构造函数
  • RequiredArgsConstructor 来自 Lombok lib 你可能应该添加 lombok 标签并在那里尝试projectlombok.org/features/Constructor.html

标签: java spring-boot autowired


【解决方案1】:

你应该用

注释你的控制器
@Controller

注释

【讨论】:

  • 嗨 Jana,感谢您的回复,但我的控制器也是我与适配器 bean 一起创建的 bean。我看到控制器中的其他属性设置正常。
  • 可能跟@Profile("!test") 有关系,那你试过不加注解吗?
【解决方案2】:

我有类似的问题:

@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;但是从私有方法中我们不能使用控制器私有字段(不仅是自动装配的,而且,例如 private Integer some_value = 12; 在此类方法中将为 null) )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-21
    • 2018-07-09
    • 2022-01-04
    相关资源
    最近更新 更多