java—我们可以使用autowire在spring中注入具有特定预定义值的类的属性吗?

rbl8hiat  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(292)

假设有一个班上的人

class Person{

private Address add;

}

class Address{
   String street;
}

当我创建person类的bean时,我需要person bean具有address属性,value street为“baker lane”。是否可以在person类中使用autowire来实现这一点,或者根本无法实现?
顺便说一下,这是个面试问题

um6iljoc

um6iljoc1#

我们可以在spring表达式中设置默认值

{表达式?:默认值}

//set deafult value for street

@Value("#{address.street ?: 'baker lane'}")
private String street;
s4n0splo

s4n0splo2#

您可以在构造函数上使用自动关联并修改person的行为。
你的面试官可能希望你能解释一下

@Component
class Person{

  private Address add;

  @Autowired
  public Person(Address add) {    <--- An instance of Address will be injected here
  this.add = add;

 //this.add.setStreet("Custom Street");  <--- you can modify that here before the Autowiring constructor ends

  /* if (add.getStreet().isEmpty()) {   <--- you can do whatever you want inside the constructor
      add.setStreet("Should not be empty") <--- you can check conditionally and set everything you want
   } */

  }

}

@Component
class Address{
   String street;
}

相关问题