spring系列的注解学习

2019-04-19  本文已影响0人  冒险小A
1.@SpringBootApplication(exclude = {xxx1.class, xxx2.class})

springboot自动配置了支持mongodb。在启动springboot时会自动实例化一个mongo实例。这不是我们想看到的。所以考虑禁用掉springboot的自动配置。
用exclude=xxx.class禁用掉springboot自带的配置
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})

2.@configuration+@import+@importResource

这些注解可以进行Spring Java config和xml的混合配置

@Configuration
    @ImportResource({"classpath*:/spring/applicationContextA.xml", "classpath*:/spring/applicationContextB.xml"})
    class ABConfigure {
    }
3.@RequestMapping,@GetMapping,PostMapping

@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。
@PostMapping是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。

@GetMapping("admin/user/{userId}")
    @ResponseBody
    public ApiResponse getUserInfo(@PathVariable(value = "userId") Long userId) {}
4.@bean

@Bean注解需在@Component、@Repository、@Controller、@Service、@Configration五个注解的类中才生效。常用在config类中。

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }
}

等同于

<beans>
    <bean id="transferService" class="com.acme.TransferServiceImpl"/>
</beans>
5.@Autowired

三种使用方法:第一种是直接在属性名上加注解,这样就可以不用在写set方法进行注入,这种方式与set方式作用一样;第二种是在set方法上加注解;第三种是在构造器上加注解

6.@ConditionalOnClass

是Springboot实现自动配置的重要支撑之一。其用途是判断当前classpath下是否存在指定类,若是则将当前的配置装载入spring容器。

7.@ConditionalOnProperty

该注解应用在config类中
通过其两个属性name以及havingValue来实现的,其中name用来从application.properties中读取某个属性值。
如果该值为空,则返回false;
如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。
如果返回值为false,则该configuration不生效;为true则生效。

@Configuration
@ConditionalOnProperty(prefix="a",name={"b","c"},havingValue = "d")
public class ConfigBean {
    //...
}
// 属性设置
a.b=d
a.c=d

都满足:即a.b=d a.c=d则生效
任何一个属性不满足则不生效
一个满足 一个不设置,此时看matchIfMissing,为true则生效,否则不生效

8.@EnableConfigurationProperties
9.@ConditionalOnMissingBean
10.@ActiveProfiles
11.@ModelAttribute
12.@ResponseBody

@responseBody的作用是将controller的方法返回的对象转换为json对象放在响应body里传给前端 , 注意是json对象而不是json字符串 , 在使用此注解之后不会再走试图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
例如User对象字段为username和password , 编写api为

@RequestMapping("/login")
  @ResponseBody
  public User login(User user){
    return user;
  }

那么在前台接收到的数据为:'{"userName":"xxx","pwd":"xxx"}'
效果等同于如下代码:

  @RequestMapping("/login")
  public void login(User user, HttpServletResponse response){
    response.getWriter.write(JSONObject.fromObject(user).toString());
  }
13.
14.
15.
16.
17.
上一篇下一篇

猜你喜欢

热点阅读