Java 第六天 Spring Annotation 和其它

时间:2022-09-05 16:48:21

Annotation,是Java语言中的一种特殊的元数据语法,Spring支持使用annotation来进行对象实例化和装配

使用Annotation在Spring的配置xml中添加context命名空间(黄色部分):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config />
<context:component-scan base-package="com.xpp"/>
</beans>

同时添加 <context:annotation-config/> 结点,如此也同时隐式注册了AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor和RequiredAnnotationBeanPostProcessor

Postprocessor: bean初始化完成之后的"处理器”

@Autowired 可以写在任何方法上

a) 默认按类型by type
b) 如果想用byName,使用@Qulifier
c) 写在private field(第三种注入形式)(不建议,破坏封装)
d) 如果写在set上,@qualifier需要写在参数上

@Required
必须在配置文件中指定并在初始化时注入

@Resource
使用JSR 250, 默认byName
a) 需要jar包:common-annotations.jar
b) 默认byName,然后byType
c) 可以指定特定名称
d) 推荐使用

Annotation表示bean

添加 <context:component-scan base-package="package.scan.root"/>

@Component, @Service, @Repository, @Controller在ApplicationContext实例化时初始化成对象,(对应配置文件中的bean)

a) 初始化的名字默认为类名首字母小写
b) 可以指定初始化bean的名字

@Scope
singleton(默认) 和 prototype

@PostConstruct @PreDestory
对应于配置文件bean的init-method和destroy-method。构造和初始化时执行的方法

一些背景知识

1. JSR – Java Specification Request
向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR,以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准。

2. JSR 250
Common Annotations for the JavaTM Platform https://jcp.org/en/jsr/detail?id=250

3. JCP
JCP - Java Community Process,一个开放的国际组织,主要由Java开发者以及被授权者组成,职能是发展和更新。

小技巧

1.将Eclipse 锁定到任务栏
在Eclipse 目录下eclipse.ini 文件-vmargs 之前加入下面2行:
-vm
C:\jdk1.7.0_45\bin

2.增强Eclipse智能提示:
打开菜单Windows-->Preferences-->Java-->Editor-->Code Assist,在Auto activation triggers for Java 栏中输入值:@.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ(,。如此输入这些字母均可触发智能提示,提高生产率。