Skip to content

Commit 377d1ec

Browse files
committed
docs(spring): add note about spring annotation
1 parent f0fc2c4 commit 377d1ec

1 file changed

Lines changed: 154 additions & 30 deletions

File tree

java/spring/spring-annotation.md

Lines changed: 154 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -98,18 +98,45 @@ public class AnnotationClass {
9898
#### Spring常用的注解有哪些
9999

100100
* 声明bean的注解
101-
* @Component 组件,没有明确的角色
102-
* @Controller 在展示层使用,控制器的声明
103-
* @RestController 在展示层使用,返回的是JSON格式的数据
104-
* @Service 在业务逻辑层使用
105-
* @Repository 在数据访问层使用
101+
* @Component 组件,没有明确的角色。作用及范围:把对象加载到spring容器中,最基础的存在,很多的注解都是继承它的,只有一个属性值,默认值是“
102+
* @Controller 在展示层使用,控制器的声明。作用及范围:作用在控制器上的注解,与Service一样,业务领域区分。可以返回string跳转jsp,ftl,html等模板页面,也可以返回实体对象
103+
* @RestController 在展示层使用,返回的是JSON格式的数据。等同于@Controller + @ResponseBody
104+
* @Service 在业务逻辑层使用。作用及范围:一般用于service层的注解,继承了Component组件,本质上一样,方便做业务范围区分而已。
105+
* @Repository 在数据访问层使用。作用及范围:作用于dao层的注解,很多经常用JPA的同学都清楚这个东西,与Service本质上一样,业务领域上区别而已
106+
```
107+
@Repository(value="userDao")注解是告诉Spring,让Spring创建一个名字叫“userDao”的UserDaoImpl实例。当Service需要使用Spring创建的名字叫“userDao”的UserDaoImpl实例时,就可以使用@Resource(name = "userDao")注解告诉Spring,Spring把创建好的userDao注入给Service即可。
108+
```
106109
* 注入bean的注解
107-
* @Autowired 由Spring提供
108-
* @Resource 由JSR-250提供
109-
* @Inject 由JSR-330提供
110+
* @Autowired 作用及范围:它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作,其实就是获取容器中的对象。通过@Autowired的使用来消除set,get方法。
111+
```
112+
注意事项:
113+
在使用@Autowired时,首先在容器中查询对应类型的bean
114+
如果查询结果刚好为一个,就将该bean装配给@Autowired指定的数据
115+
如果查询的结果不止一个,那么@Autowired会根据名称来查找。
116+
如果查询的结果为空,那么会抛出异常。解决方法时,使用required=false
117+
```
118+
* @Resource 由JSR-250提供,根据名称进行自动装配的,一般会指定一个name属性,可以作用在变量、setter方法上。
119+
* @Inject 由JSR-330提供需要导入javax.inject.Inject;实现注入,根据类型byType进行自动装配的,如果需要按名称进行装配,则需要配合@Named,可以作用在变量、setter方法、构造函数上。很少用。
110120
* java配置类相关注解
111-
* @Configuration 声明当前类为配置类,相当于xml形式的Spring配置
112-
* @Bean 注解在方法上,声明当前方法的返回值为一个bean, 替代xml的方式
121+
* @Configuration 声明当前类为配置类,相当于xml形式的Spring配置。用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法
122+
* @Bean 注解在方法上,声明当前方法的返回值为一个bean, 替代xml的方式。@Bean:Spring的@Bean注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。产生这个Bean对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的IOC容器中。SpringIOC 容器管理一个或者多个bean,这些bean都需要在@Configuration注解下进行创建,在一个方法上使用@Bean注解就表明这个方法需要交给Spring进行管理。
123+
```
124+
@Configuration
125+
public class AppConfig {
126+
// 未指定bean 的名称,默认采用的是 "方法名" + "首字母小写"的配置方式
127+
@Bean
128+
public MyBean myBean(){
129+
return new MyBean();
130+
}
131+
}
132+
133+
public class MyBean {
134+
135+
public MyBean(){
136+
System.out.println("MyBean Initializing");
137+
}
138+
}
139+
```
113140
* @Scope注解设置Spring容器如何新建Bean实例
114141
* Singleton 默认模式,单例,一个Spring容器中只有一个bean实例
115142
* Protetype 每次调用新建一个bean
@@ -118,8 +145,7 @@ public class AnnotationClass {
118145
* GlobalSession(给每个global http session新建一个bean实例)
119146
* @PostConstruct由JSR-250提供,在构造函数执行完之后执行,等价于xml中bean配置的的initMethod
120147
* @PreDestory由JSR-250提供,在Bean销毁之前执行,等价于xml中bean配置的destroyMethod
121-
* @Configuration 声明当前类为配置类,其中内部组合了@Component注解,表明这个类是一个bean
122-
* @ComponentScan用于对Component进行扫描,替代xml的方式
148+
* @ComponentScan用于对Component进行扫描,替代xml的方式。作用及范围:扫描当前类下面的所有对象,为什么说Component是最基础的东西,就是要给这个注解扫描,非常巧妙的设计,可以扫描多个包。
123149
* @WishlyConfiguration为@Configuration与@ComponentScan的组合注解,用的很少
124150
* 切面(AOP)相关注解
125151
* @Aspect声明一个切面(类上),使用@After,@Before,@Around定义建言(advice),可直接将拦截规则(切点)作为参数。在java配置类中使用@EnableAspectJAutoProxy注解开启Spring对AspectJ代理的支持(类上)
@@ -129,28 +155,126 @@ public class AnnotationClass {
129155
* @PointCut声明切点
130156
* 环境切换
131157
* @Profile通过设定Environment的ActiveProfiles来设定当前context需要使用的配置环境(类或者方法上)
158+
```java
159+
@PropertySource("classpath:/user.properties")
160+
@Configuration
161+
public class MainConfigOfProfile implements EmbeddedValueResolverAware{
162+
163+
@Profile("test")
164+
@Bean("testUser")
165+
public User testUser() {
166+
User a =new User();
167+
return a;
168+
}
169+
170+
@Profile("dev")
171+
@Bean("devUser")
172+
public User devUser() {
173+
User a =new User();
174+
return a;
175+
}
176+
}
177+
```
132178
* @Conditional使用此注解定义激活bean的条件,通过实现Condition接口,并重写matches方法,从而决定该bean是否被实例化(方法上)
179+
```java
180+
@Configuration
181+
public class BeanConfig {
182+
183+
//只有一个类时,大括号可以省略
184+
//如果WindowsCondition的实现方法返回true,则注入这个bean
185+
@Conditional({WindowsCondition.class})
186+
@Bean(name = "bill")
187+
public Window window(){
188+
return new Window();
189+
}
190+
191+
//如果LinuxCondition的实现方法返回true,则注入这个bean
192+
@Conditional({LinuxCondition.class})
193+
@Bean("linux")
194+
public Linex linux(){
195+
return new Linex();
196+
}
197+
}
198+
```
133199
* 配置注解
134200
* @Value注解
135-
* 普通字符串 `@Value("xxxx")`
136-
* 操作系统属性 `@Value("#{systemProperties['os.name']}")`
137-
* 注入表达式 `@Value("#{T(java.lang.Math).random() * 100}")`
138-
* 注入bean属性 `@Value("#{xxxClass.name})`
139-
* 注入文件资源
140201
```java
141-
@Value("classpath:com/zhonghausheng/value/test.txt")
142-
Resource file;
143-
```
144-
* 注入url
145-
```java
146-
@Value("http://")
147-
Resource url;
148-
```
149-
* 配置文件
150-
```java
151-
@Value("${book.name}")
152-
String bookName;
202+
@Value("normal")
203+
private String normal; // 注入普通字符串
204+
205+
@Value("#{systemProperties['os.name']}")
206+
private String systemPropertiesName; // 注入操作系统属性
207+
208+
@Value("#{ T(java.lang.Math).random() * 100.0 }")
209+
private double randomNumber; //注入表达式结果
210+
211+
@Value("#{beanInject.another}")
212+
private String fromAnotherBean; // 注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面
213+
214+
@Value("classpath:com/hry/spring/configinject/config.txt")
215+
private Resource resourceFile; // 注入文件资源
216+
217+
@Value("http://www.baidu.com")
218+
private Resource testUrl; // 注入URL资源
153219
```
154-
* @PropertySource加载配置文件(类上),`@PropertySource("classpath:com/zhonghuasheng/value/test.properties")`
220+
* @PropertySource加载配置文件(类上)
221+
```java
222+
@PropertySource(value = {"classpath:test.properties"})
223+
@Component
224+
@ConfigurationProperties(prefix = "test")
225+
public class Test {
226+
private Integer id;
227+
private String lastName;
228+
}
229+
```
230+
231+
* 异步相关
232+
* @EnableAsync 配置在类上,开启对异步任务的支持
233+
* @Async在实际执行的bean方法使用该注解来申明其是一个异步任务(方法上或类上的所有方法都将异步,需要@EnableAsync开启异步任务)
234+
* 定时任务
235+
* @EnableScheduling 配置在类上,开启计划任务的支持
236+
* @Scheduled声明这是一个任务,包括cron, fixDelay, fixRate等类型,用于方法上,需要先开启计划任务的支持
237+
* Enable*注解
238+
* @EnableAspectJAutoProxy开启对AspectJ自动代理的支持
239+
* @EnableAsync开启异步方法的支持
240+
* @EnableScheduling开启计划任务的支持
241+
* @EnableWebMvc开启Web MVC的配置支持
242+
* @EnableConfigurationProperties开启对@ConfigurationProperties注解配置Bean的支持
243+
* @EnableJpaRepositories开启对SpringData JPA Repository的支持
244+
* @EnableTransactionmanagement开启注解式事务的支持
245+
* @EnableCaching开启注解式的缓存支持
246+
* 持久层注解
247+
* @TableField(value="数据表字段", exist=true/false) 表示该属性为数据库表字段
248+
* @TableName:数据库表相关
249+
* @TableId:表主键标识
250+
* @JsonIgnore:作用是json序列化时将Java bean中的一些属性忽略掉,序列化和反序列化都受影响
251+
* @JsonProperty用于将参数中的字段转换为DTO的字段
252+
* 其他注解
253+
* @CrossOrigin用于class和method上用来支持跨域请求
254+
* @ExceptionHandler用于方法级别,声明对Exception的处理逻辑
255+
* @ControllerAdvice全局异常处理,全局数据绑定,全局数据预处理
256+
```java
257+
@ControllerAdvice
258+
public class MyGlobalExceptionHandler {
259+
@ExceptionHandler(Exception.class)
260+
public ModelAndView customException(Exception e) {
261+
ModelAndView mv = new ModelAndView();
262+
mv.addObject("message", e.getMessage());
263+
mv.setViewName("error");
264+
return mv;
265+
}
266+
}
267+
268+
@ControllerAdvice
269+
public class MyGlobalExceptionHandler {
270+
@ModelAttribute(name = "md")
271+
public Map<String,Object> mydata() {
272+
HashMap<String, Object> map = new HashMap<>();
273+
map.put("gender", "女");
274+
return map;
275+
}
276+
}
277+
```
278+
155279
### 参考文章
156280
* http://m.biancheng.net/view/7009.html

0 commit comments

Comments
 (0)