自定义类似@Required功能的注解

自定义类似@Required功能的注解

   我们知道被@Required标注的方法是必须有值的,否则报异常,我们如何自定义了

  这种非常简单,只需要向RequiredAnnotationBeanPostProcessor类中注册即可

   我的自定义注解类是:

  

  package liusheng.dao;

  import java.lang.annotation.ElementType;
  import java.lang.annotation.Retention;
  import java.lang.annotation.RetentionPolicy;
  import java.lang.annotation.Target;

  @Retention(RetentionPolicy.RUNTIME)
  @Target(value=ElementType.METHOD)
  public @interface MyAnnotation {

  }

 配置文件是:

            

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor">
        <property name="requiredAnnotationType" value="liusheng.dao.MyAnnotation"/>
    </bean>

    


    <bean class="liusheng.dao.User">
    <property name="name" value="12"></property>
    <property name="password" value="12"></property>
  </bean>


<context:component-scan base-package="liusheng.dao"/> </beans>

  实体类是:

  

package liusheng.dao;

import org.springframework.beans.factory.annotation.Required;

public class User {
        
        private String name;
        
        private String password;
        public String getName() {
            return name;
        }
        @MyAnnotation
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPassword() {
            return password;
        }
        @MyAnnotation
        public void setPassword(String password) {
            this.password = password;
        }
        public String toString() {
            return "User [name=" + name + ", password=" + password + "]";
        }
        
}

 注意:@Required与@MyAnnotation只有注解在方法上才有效,

 测试类:

  

package liusheng.dao;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/java/applicationContext.xml")

public class SanTest {
    @Autowired
    User user;
    @Test
    public void test(){
        System.out.println(user);
    }

}

 结果:

  

 

  

  虽然这样的用处不是很大,但是Spring中很多对象可以自定义,表示了Spring很灵活

    

    

posted on 2018-03-19 00:43  学习spring是我必须的  阅读(236)  评论(0编辑  收藏  举报