Spring IoC 注解配置

使用注解类:

需要在配置中添加context命名空间:如下


xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=".. http://www.springframework.org/schema/context
http://springframework.org/schema/context/spring-context-3.0.xsd.."
使用:



<context:component-scan base-package="包路径" >
	<context:include-fileter type="类型" expression="匹配" /> <!--包含匹配-->
	<context:exclude-filter type="类型" expression="匹配路径" /> <!--排除匹配-->
</context:component-scan>
过滤表达式: 详见过滤表达式篇(待添加= =)


基于注解的配置

标示:

@Component("xx") 

public class Entity..

等价 <bean id="xx" class="com.bean.Entity" />

类似@Component的有@Repository @Service @Controller 对应mvc3个层次

自动装配:

@Autowired([requied=false|true])  

requied属性标示 是否必须有此类型  true如果找不到这个类型则报出异常

@Qualifire("bean id");

指定要注入的类的类名,此注释可以注释在参数上

Bean的作用范围注释:

@Scope("范围名");

范围名:prototype singleton request session globalSession

检测属性是否设置:

@Required 设置此注解的属性必须初始化

生命周期

@PostConstruct

载入配置文件时运行

@PreDestory

关闭到时候运行

基于Java类的配置

@Configuration 

在类上标注,为Spring容器提供Bean定义的信息

@bean 

给方法标注,此方法提供Bean的实例化

Spring会对标注@bean的方法进行AOP改造,使之进行AOP注入操作

例如:


@Configuration
public class A {
	@Bean
	public B getB(){
		return new B();
	}
	public Login logonService(){
		Login login=new Login();
		login.setB(getB());
	}
}
等同xml配置:



<bean id="a" class="xxxx.A" /> 
<bean id="logon" class="xxxx.Login" p:getB-ref="a" />

即A类提供对login类中的方法进行依赖注入


@Configruation有@Component注解的含义

即@Configruation会被context:component-scan所自动扫描入容器

基于注解的java属性配置

需要在配置文件中加入,导入的properties文件

<context:propterty-placeholder location="properties的位置" />

然后再类属性加入注解

@Value("${properties的key名}")

引用类的属性:

@Value("#{beanName.property}")




















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值