SpringBoot 常用注解

2020-05-10  本文已影响0人  8090的大叔

这类常用注解中,不仅有SpringBoot自有的,也有一部分继承Spring的。


/* @SpringBootApplication 组合型注解
 * @SpringBootConfiguration:标注当前类是配置类,继承自@Configuration,并且将当前类内部声明的@Bean标记的方法实例纳入到Spring容器进行管理
 * @ComponentScan:扫描当前包下子包中包含@Controller、@Service、@Repository、@Component注解标记的类纳入到Spring容器中进行管理
 * @EnableAutoConfiguration:自动配置注解,根据添加的组件jar完成默认配置。
 * */
@SpringBootApplication(exclude = {WebAutoConfiguration.class})

/* @MapperScan 扫描多个指定包中的接口 */
@MapperScan({"com.*.dao","com.test"})
class Application {
    /* @Value 将外部值动态注入*/
    @Value("spring.appplication.name")
    private String appName;
}

/* @Component 通用注解,表示通用Bean @Controller @Service @Repository 中都存在@Component注解,只是作为业务区分*/
@Component
/* @Controller 标识当前类是一个控制器*/
@Controller("/base")
/* @RestController 组合注解  @Controller 和 @ResponseBody 的组合*/
@RestController
/* @Scope 注释类,Spring容器管理Bean的方式 singleton(单例)、prototype(多例)*/
@Scope("prototype")
class controller{
    /* 自动装配注解 byType*/
    @Autowired
    /* 配合@Autowired使用,将byType转为byName*/
    @Qualifier("userService")
    UserService userService;
    /* J2EE的注解 byName装配*/
    @Resource(name = "userDao")
    UserDao userDao;

    /* @RequestMapping URL映射*/
    @RequestMapping(value="/ctl/{userId}",method= RequestMethod.GET )

    /* 对于@RequestMapping的简写 ,简化 method
    *  @GetMapping @PostMapping @PutMapping @DeleteMapping */
    @GetMapping("getCtl")
    @PostMapping("postCtl")
    @PutMapping("putCtl")
    @DeleteMapping("deleteCtl")

    /* @ResponseBody 标识备注解方法可以返回JSON */
    @ResponseBody

    /* @PathVariable 获取URL中{}的参数,一般{ }中的变量名与方法中的形参名一致(可以不加@PathVariable注解)*/
    /* @RequestParam 用来处理Content-Type为application/x-www-form-urlencoded(默认类型如果不指定),使用value属性可以指定获取参数的key */
    Map method(@PathVariable("userId") String userId,@RequestParam("userName") String userName){
        return new HashMap();
    }
}

/* @Service 标注当前类是一个业务层组件 */
@Service
class UserService{
    /* @Trancational 事务注解,标注的方法开启事务管理*/
    @Transactional(isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
    void method(){}
}

/* @Repository 标注当前类是DAO对象,管理操作数据库的对象 */
@Repository
class UserDao{}

/* @EnableCaching Spring3.1加入,开启Spring缓存管理器  等同于 <cache:annotation-driven/>*/
@EnableCaching
class EhCacheConfig {
    /* @Bean: 注解在方法上,声明当前方法返回一个Bean*/
    @Bean
    UserDao method(){
        return new UserDao();
    }
}

/* @EnableScheduling 启动Spring自带的定时服务*/
@EnableScheduling
class SpringTasks{
    /* 注解的方法 会定时执行,可配置具体定时规则 */
    @Scheduled(fixedRate = 5000)
    void task(){}
}

public class TestAnnotate {
}
上一篇下一篇

猜你喜欢

热点阅读