自定义类似@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 { }配置文件是:
<bean class="liusheng.dao.User">
<property name="name" value="12"></property> <property name="password" value="12"></property> </bean>实体类是:
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很灵活