Java笔记Spring(三)

时间:2024-01-05 17:14:14

spring-beans和spring-context

一、注解

1、自定义一个注解

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() default "";
}

2、使用注解

public class MyClass {
@MyAnnotation("注解参数")
public String get() {
return "呵呵";
}
}

3、注解被调用,测试

public class AnnotationTest {
@Test
public void get() throws NoSuchMethodException {
MyAnnotation myAnnotation = MyClass.class.getDeclaredMethod("get", null).getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation.value());
}
}

4、结果

Java笔记Spring(三)

二、 Assert(断言,JDK1.4)

Java笔记Spring(三)

public class AnnotationTest {

    @Test
public void get() throws NoSuchMethodException {
MyAnnotation myAnnotation = MyClass.class.getDeclaredMethod("get", null).getAnnotation(MyAnnotation.class);
Assert.assertEquals(myAnnotation.value(), "注解参数");
System.out.println("程序正常");
}
}

三、Spring中的注解

常用的:

spring-context包下:

@Component

@Repository

@Service

@Controller

@Bean

@ComponentScan

@Configuration

@EnableScheduling

@Scheduled

spring-beans包下:

@Autowired

@Configurable

@Qualifier

@Value