How to make an autowire class with a non-empty constructor?

I would like a @Autowiredclass with a non-empty constructor. Only the following can be cited as an example: this does not have to be a view / service. There may be any component you like with a custom constructor:

@Component
class MyViewService {
  //the "datasource" to show in the view
  private List<String> companies companies;
  private MyObject obj;

  public MyViewService(List<String> companies, MyObject obj) {
    this.companies = companies;
    this.obj = obj;
  }
}

Of course I can’t just write

@Autowired
private MyViewService viewService;

since I would like to use a list constructor. But how?

Are there any better approaches than refactoring these constructors to setters? I would not like this approach, because ideally the constructor forces other classes to provide all the objects that are needed in the service. If I use setters, I can easily forget to set certain objects.

0
2

Spring MyViewService, Spring, . XML:

<bean id="myViewService" class="org.membersound.MyViewService">
  <constructor-arg index="0" ref="ref_to_list" />
  <constructor-arg index="1" ref="ref_to_object" />
</bean>

Java, @Bean.

Spring docs . , , bean XML, Spring. (, , ), factory bean.

, , , Spring:)

+2

, bean.

XML, ( spring ):

<beans>
    <bean id="foo" class="x.y.Foo">
        <constructor-arg ref="bar"/>
        <constructor-arg ref="baz"/>
    </bean>

    <bean id="bar" class="x.y.Bar"/>
    <bean id="baz" class="x.y.Baz"/>
</beans>

- bean, @AutoWire. bean .

0

Source: https://habr.com/ru/post/1659834/


All Articles