您的位置:首页 > 职场人生

真实企业JAVA面试题

2018-03-08 17:31 441 查看
请举例解释@Required annotation?在产品级别的应用中,IoC容器可能声明了数十万了bean,bean与bean之间有着复杂的依赖关系。设值注解方法的短板之一就是验证所有的属性是否被注解是一项十分困难的操作。可以通过在<bean>中设置“dependency-check”来解决这个问题。在应用程序的生命周期中,你可能不大愿意花时间在验证所有bean的属性是否按照上下文文件正确配置。或者你宁可验证某个bean的特定属性是否被正确的设置。即使是用“dependency-check”属性也不能很好的解决这个问题,在这种情况下,你需要使用@Required 注解。需要用如下的方式使用来标明bean的设值方法。public class EmployeeFactoryBean extendsAbstractFactoryBean<Object>{   private String designation;    public String getDesignation() {       return designation;   }    @Required   public void setDesignation(String designation) {       this.designation = designation;   }    //more code here}RequiredAnnotationBeanPostProcessor是Spring中的后置处理用来验证被@Required 注解的bean属性是否被正确的设置了。在使用RequiredAnnotationBeanPostProcesso来验证bean属性之前,首先要在IoC容器中对其进行注册:<beanclass="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>但是如果没有属性被用 @Required 注解过的话,后置处理器会抛出一个BeanInitializationException 异常。20、请举例解释@Autowired注解?@Autowired注解对自动装配何时何处被实现提供了更多细粒度的控制。@Autowired注解可以像@Required注解、构造器一样被用于在bean的设值方法上自动装配bean的属性,一个参数或者带有任意名称或带有多个参数的方法。比如,可以在设值方法上使用@Autowired注解来替代配置文件中的 <property>元素。当Spring容器在setter方法上找到@Autowired注解时,会尝试用byType 自动装配。当然我们也可以在构造方法上使用@Autowired 注解。带有@Autowired 注解的构造方法意味着在创建一个bean时将会被自动装配,即便在配置文件中使用<constructor-arg> 元素。public class TextEditor {  private SpellChecker spellChecker;   @Autowired  public TextEditor(SpellChecker spellChecker){     System.out.println("Inside TextEditor constructor." );     this.spellChecker = spellChecker;  }   public void spellCheck(){     spellChecker.checkSpelling();  }}下面是没有构造参数的配置方式:<beans>   <context:annotation-config/>   <!-- Definition for textEditor bean without constructor-arg  -->  <bean id="textEditor"class="com.howtodoinjava.TextEditor">  </bean>   <!-- Definition for spellChecker bean -->  <bean id="spellChecker"class="com.howtodoinjava.SpellChecker">  </bean> </beans>21、请举例说明@Qualifier注解?@Qualifier注解意味着可以在被标注bean的字段上可以自动装配。Qualifier注解可以用来取消Spring不能取消的bean应用。下面的示例将会在Customer的person属性中自动装配person的值。public class Customer{   @Autowired   private Person person;}下面我们要在配置文件中来配置Person类。<bean id="customer"class="com.howtodoinjava.common.Customer" /> <bean id="personA" class="com.howtodoinjava.common.Person">   <property name="name" value="lokesh" /></bean> <bean id="personB"class="com.howtodoinjava.common.Person" >   <property name="name" value="alex" /></bean>Spring会知道要自动装配哪个person bean么?不会的,但是运行上面的示例时,会抛出下面的异常:Caused by:org.springframework.beans.factory.NoSuchBeanDefinitionException:   No unique bean of type [com.howtodoinjava.common.Person] is defined:       expected single matching bean but found 2: [personA, personB]要解决上面的问题,需要使用 @Quanlifier注解来告诉Spring容器要装配哪个bean:public class Customer{   @Autowired   @Qualifier("personA")   private Person person;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JAVA面试 面试题