spring注解简化配置

组件扫描

package annotation;

import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("sb1")
@Scope("singleton")
@Lazy(true)
/**
 * 获取bean时,首字母小写
 */
public class SomeBean {

}

配置组件扫描

	<!-- 
		base-package属性:指定要扫描的包名,spring容器会扫描该包及其子包下面所有的类
		如果该类前面有特定的注解,(比如@Component)则spring容器会将其纳入容器进行管理(相当于这配置了一个bean元素)
	 -->
	<context:component-scan base-package="annotation"/>

依赖注入相关的注解

@PostConstruct和@PreDestroy


package annotation;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("sb1")
@Scope("singleton")
@Lazy(true)
/**
 * 获取bean时,首字母小写
 * @author Administrator
 *
 */
public class SomeBean {
	//初始化方法
	@PostConstruct
	public void init(){
		System.out.println("init()");
	}
	//销毁方法
	@PreDestroy
	public void destroy(){
		System.out.println("destroy()");
	}
	public SomeBean() {
		System.out.println("SomeBean()");
	}
}


@Autowired和@Qualifier


package annotation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;


@Component("rest")
public class Restaurant {
//	@Autowired
//	@Qualifier("wt")
// 加在前面,spring可以通过反射,跳过set方法
	private Waiter wt;
	
	public Waiter getWt() {
		System.out.println("getWt()");
		return wt;
	}

	@Autowired
	public void setWt(@Qualifier("wt") Waiter wt) {
		System.out.println("setWt()");
		this.wt = wt;
	}

	public Restaurant() {
		System.out.println("Restaurant()");
	}
}

@Resource

package annotation;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

@Component("bar")
public class Bar {
	private Waiter wt;

	public Bar() {
		System.out.println("Bar()");
	}

	@Resource(name="wt")
	public void setWt(Waiter wt) {
		System.out.println("setWt()");
		this.wt = wt;
	}
}

@Value

package annotation;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("mg")
public class Manager {
	@Value("#{config.pageSize}")
	private String pageSize;
	@Value("花千骨")//给name赋值
	private String name;

	public Manager() {
		System.out.println("Manager()");
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值