需要时创建服务实例

时间:2018-02-27 13:47:42

标签: spring-boot autowired

我有一个映射请求网址的Controller类。我有一个用@Service注释的类实例。例如;

@Controller
class MainController{
  @Autowired
  private UserService userService;
  ...
}

据我所知,这个实例是由Spring容器自动创建的,因为我添加了@Autowired但是在方法中遇到条件时我使用了这个实例。如果不满足条件,我不需要这个实例。因此,这个声明是开销。我的意思是,即使它被创建,我也可能不会使用它。

我想在需要时创建对象。我怎么能在代码中这样做?我可能不会使用@Autowired,因为我需要动态对象创建。我还需要做什么?

2 个答案:

答案 0 :(得分:0)

您可以使用Setter注射。 @Autowired注释可用于setter方法。在下面的示例中,当在setter方法上使用注释时,将在创建FooService时使用FooFormatter实例调用setter:

public class FooService {

private FooFormatter fooFormatter;

@Autowired
public void setFooFormatter(FooFormatter fooFormatter) {
        this.fooFormatter = fooFormatter;
}
}

通过这种方式,您可以在明确调用setter方法时为您注入服务:)希望这会对您有所帮助:)

稍后编辑

我找到了一种可以解决问题的方法,它被命名为@Lazy。

您可以像这样使用@Lazy注释:

  1. 在服务类上,将@Lazy注释放在公共类XXX定义之前;

    1. 在控制器上下文中声明/自动装配服务类型时,将@Lazy注释与@Autowired注释放在声明的属性之上,如
    2. @Lazy @Autowired 私人FooFormatter fooFormatter;

      有关详细信息,请查看链接:http://www.baeldung.com/spring-lazy-annotation

答案 1 :(得分:0)

您需要将@Lazy注释与Bean生命周期注释结合使用。但是,您需要考虑的一件事是控制器的性能,如果您每次需要时都重新创建服务,则会降低性能。