Spring简介注解1

67 阅读2分钟

1.@Configuration注解

该类等价 与XML中配置beans,相当于Ioc容器,它的某个方法头上如果注册了@Bean,就会作为这个Spring容器中的Bean,与xml中配置的bean意思一样。

@Configuration注解的类必需使用扫描.如下:

@Configuration
public class MainConfig {

//在properties文件里配置
    @Value("${wx_appid}")
public String appid;
 protected MainConfig(){}

@Bean
public WxMpService wxMpService() {
    WxMpService wxMpService = new WxMpServiceImpl();
    wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
    return wxMpService;
    }
}

定义一个MainConfig,用@Configuration注解,那MainConfig相当于xml里的beans,里面用@Bean注解的和xml里定义的bean等价,用扫描该类,最终我们可以在程序里用@AutoWired或@Resource注解取得用@Bean注解的bean,和用xml先配置bean然后在程序里自动注入一样。目的是减少xml里配置。

2.@Vaue注解

为了简化从properties里取配置,可以使用@Value, 可以在properties文件中的配置值。

在dispatcher-servlet.xml里引入properties文件。

<context:property-placeholder location="classpath:test.properties" />

在程序里使用@Value:

@Value("${wx_appid}")

public String appid;

即使给变量赋了初值也会以配置文件的值为准。

3.@Controller,@Service,@Repository,@Component

目前4种注解意思是一样,并没有什么区别,区别只是名字不同。使用方法:

1.使用扫描被注解的类

2.在类上写注解:

@Controller

public class TestController {



}

4. @PostConstruct 和 @PreDestory

实现初始化和销毁bean之前进行的操作,只能有一个方法可以用此注释进行注释,方法不能有参数,返回值必需是void,方法需要是非静态的。

例如:

public class TestService {
@PostConstruct  
public void  init(){  
    System.out.println("初始化");  
}

@PreDestroy  
public void  dostory(){  
    System.out.println("销毁");  
}  
}

@PostConstruct:在构造方法和init方法(如果有的话)之间得到调用,且只会执行一次。

@PreDestory:注解的方法在destory()方法调用后得到执行。 引深一点,Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,常用的设定方式有以下三种:

1.通过实现 InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法;

2.通过 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法;

3.在指定方法上加上@PostConstruct 或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用

但他们之前并不等价。即使3个方法都用上了,也有先后顺序.

Constructor > @PostConstruct >InitializingBean > init-method

5. @Primary

自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常。

例如:

@Component  
public class Apple implements Fruit{  
@Override  
public String hello() {  
    return "我是苹果";  
    }  
}
@Component  
@Primary
public class Pear implements Fruit{  
@Override  
public String hello(String lyrics) {  
    return "梨子";  
    }  
}
public class FruitService {

  //Fruit有2个实例子类,因为梨子用@Primary,那么会使用Pear注入
    @Autowired  
    private Fruit fruit;  
public String hello(){  
    return fruit.hello();  
    }  
}

6. @Lazy(true)

用于指定该Bean是否取消预初始化,用于注解类,延迟初始化。

7. @Autowired

Autowired默认先按byType,如果发现找到多个bean,则,又按照byName方式比对,如果还有多个,则报出异常。

1.可以手动指定按byName方式注入,使用@Qualifier。

//通过此注解完成从spring配置文件中 查找满足Fruit的bean,然后按//@Qualifier指定pean

@Autowired

@Qualifier("pean")

public Fruit fruit;

2.如果要允许null 值,可以设置它的required属性为false,如:

@Autowired(required=false)

public Fruit fruit;