1. autowired与resource:@Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按 byName自动注入罢了。@Resource有两个属性是比较重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。
@Resource装配顺序
1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹 配,如果匹配则自动装配;
2.
2.@Value注解
为了简化从properties里取配置,可以使用@Value, 可以properties文件中的配置值。
在dispatcher-servlet.xml/spring-config.xml里引入properties文件。
- <context:property-placeholder location="classpath:test.properties" />
-
或者<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:conf/db.properties</value>
<value>classpath:conf/business.properties</value>
<value>classpath:conf/elasticsearch.properties</value>
<value>classpath:escluster.properties</value>
<value>classpath:conf/cat.consumer.properties</value>
</list>
</property>
</bean>
在程序里使用@Value:
@Value("${wx_appid}")
public String appid ;
即使给变量赋了初值也会以配置文件的值为准。
3.@Controller, @Service, @Repository,@Component
如果 Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用上述注解对分层中的类进行注释。
@Service用于标注业务层组件
@Controller用于标注控制层组件(如struts中的action)
@Repository用于标注数据访问组件,即DAO组件
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注
如果想自定义,可以@Service(“aaaaa”)这样来指定。这种bean默认是“singleton”的,如果想改变,可以使用@Scope(“prototype”)来改变。
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.通过 <bean> 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法;
3.在指定方法上加上@PostConstruct 或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用
但他们之前并不等价。即使3个方法都用上了,也有先后顺序.
Constructor > @PostConstruct >InitializingBean > init-method
文章部分借鉴自:http://blog.csdn.net/achenyuan/article/details/72786759
http://blog.csdn.net/zhang854429783/article/details/6785574