组件扫描
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()");
}
}