spring framework手动装配
spring模式注解装配:用于声明在应用中扮演“组件”角色的注解,例如@Component @Servbice @Configuration等。例如:
spring framework中,任何标记@Repository注释的类都是实现了仓储角色的模式注解。@Component标注在任何一个类上,标识这个类是可扫描的对象。
spring framework注解举例:
@Repository:数据仓储模式注解(DAO)
@Component:通用组件模式注解
@Service:服务模式注解
@Controller:Web控制器模式注解
@Configuration:配置类模式注解
装配方式
xml:
<?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/springcontext.xsd">
<!-- 激活注解驱动特性 -->
<context:annotation-config />
<!-- 找寻被 @Component 或者其派生 Annotation 标记的类(Class),将它们注册为 Spring Bean -->
<context:component-scan base-package="com.haozirou.demo" />
</beans>
注解:
@ComponentScan(basePackages = "com.haozirou.demo")
public void SrpingConfiguration {
...
}
自定义模式注解
@Component派生性
import java.lang.annotation.*;
import org.springframework.stereotype.Repository;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repository
public @interface First {
String value() default "";
}
@First标记了@Repository,@Repository中标记了@Component
自定义注解方式:
运行结果:
@Component方式:
运行结果:
由此可见,使用自定义注解和@Component注解运行效果一样,因为@First继承了@Repository,也继承了@Component,同时注解的签名方法一致,都是String value() default "";这就是@Component的派生性
@Component层次性
自定义另一个注解,标注@First,那么也会具有@Fisrt的属性,具有层次,就是层次性。
常见注解:
@Component
·@Configuration
·@SpringBootConfiguration
·&#