如何通知Spring必须填充Bean属性?

时间:2011-04-16 05:05:45

标签: java spring annotations javabeans

假设我有一个像这样的Java类:

public class PersonGrabber {
  private PersonDAO dao;

  public void setDao(PersonDao dao) {
    this.dao = dao;
  }
  public PersonDAO getDao() {
    return this.dao;
  }
  //...
}

我有一个相应的Spring bean:

<bean id="personGrabber" class="com.stackoverflow.example.PersonGrabber">
  <property name="dao"><null/></property>
</bean>

现在,这很糟糕,因为我真的需要在该bean变得有用之前将dao属性设置为该bean的内容。但是,我不想等到运行时等待它抛出NullPointerException。反正有没有告诉Spring在使用之前填充bean属性必须?理想情况下,我希望它在初始化时崩溃,以便我不必等待它找出来。

我希望有类似注释的内容:

public class PersonGrabber {
  @SpringRequired
  private PersonDAO dao;
  //...
}

一些春季退伍军人的帮助吗?

4 个答案:

答案 0 :(得分:5)

对于你所拥有的类的类型,总是需要将其他属性设置为非空值,执行此操作的最简单方法是双重操作。使用setter上的@Required注释告诉Spring必须始终调用该方法,并在setter中检查注入是否是真实实例(即,不是null)。

@Required
public void setDao(PersonDao dao) {
    if (dao == null)
        throw new IllegalArgumentException("property 'dao' is null");
    this.dao = dao;
}

最后一点是你需要确保在Spring配置文件中打开注释处理:

<context:annotation-config/>

请注意,你很可能已经有了这个。

答案 1 :(得分:3)

您要查找的注释是@Required

您还可以使用bean上的init-method属性指向在填充所有属性后调用的方法。这将允许您执行后期设置验证。

答案 2 :(得分:2)

另一种方法是将bean类声明为实现InitializingBean,并实现afterPropertiesSet方法以检查属性是否已设置为可接受的值。

答案 3 :(得分:0)

使用spring进行JSR 303验证怎么样?你有问题吗??

链接here,万一您以前没见过。