Spring 注解的理解

@Autowired
自动注入,从Spring上下文找到合适的bean来注入,默认按照类型来装配bean,bean必须存在,如果为null,使用required属性为false,@Autowired(required=false),如果想按照名字来装配,使用:@Autowired @Qualifier("beanName");特殊使用:当@Autowired注解用来注入map或者list的时候:

@Autowired
private Map<String, Strategy> map = new ConcurrentHashMap<>();

value的泛型为Strategy,则spring将注入到容器里的bean放入value,key则为bean的名称。如:

@Component("1")
public class ConcreteStrategy1 implements Strategy {

    @Override
    public void handle() {
        System.out.println("test ConcreteStrategy1");
    }
}

那么这个map就是(1,ConcreteStrategy1的bean)。list类似。这种方式可以用来实现策略模式,避免多个if-else。

 

@Resource
按照名称注入bean,使用:@Resource(name="beanName"),这个注解是JDK提供的,而@Autowired是Spring提供的。

 

@Controller与@RestController
标识为控制层组件,返回页面使用@Controller,返回数据使用@RestController,@RestController等同于@Controller+@ResponseBody 它会自动把对象实体转换为JSON格式。

//这是使用@RestController,返回数据,包装成了ResponseVO,异常统一处理
@RestController
@RequestMapping("/api")
public class RestApiController {

    @PostMapping("/comments")
    @BussinessLog(value = "评论列表", platform = PlatformEnum.WEB, save = false)
    public ResponseVO comments(CommentConditionVO vo) {
        vo.setStatus(CommentStatusEnum.APPROVED.toString());
        return ResultUtil.success(null, commentService.list(vo));
    }

}

//这是使用@Controller,返回页面 ModelAndView
@Controller
public class RenderController {

    @GetMapping("/type/{typeId}")
    @BussinessLog(value = "进入文章分类[{1}]列表页", platform = PlatformEnum.WEB)
    public ModelAndView type(@PathVariable("typeId") Long typeId, Model model) {
        ArticleConditionVO vo = new ArticleConditionVO();
        vo.setTypeId(typeId);
        model.addAttribute("url", "type/" + typeId);
        loadIndexPage(vo, model);

        return ResultUtil.view(INDEX_URL);
    }

}

 

@Service @Repository 分别标记Service层类(业务层),数据存储层类(如Mapper),Spring扫描注解配置时,会标记这些类要生成bean

 

@Component :
通用注释,说明这个类是一个Spring容器管理的类,这个类将被Spring IoC容器扫描装配,@Component("user"),“user”则作为Bean的名称,如果不配置括号里的内容,IoC容器会把类名的第一个字母小写,其余不变,作为Bean名称放入IoC容器。@Controller,@Service,@Repository都是@Component的细化

 

@Bean
是一个方法级别的注解,主要用在@Configuration注解的类中,@Bean(name="redisTemplate") ,生成一个叫redisTemplate的Bean,装配到IOC容器中,如果没有(name="redisTemplate") ,那么,方法名即为生成的Bean的id,实例:

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String,Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(mapper);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

 

@PathVariable
从request请求中接收参数,从URL中取值,参数值需要在URL中占位

    @PostMapping("/doSupport/{id}")
    @BussinessLog(value = "点赞评论{1}", platform = PlatformEnum.WEB)
    public ResponseVO doSupport(@PathVariable("id") Long id) {
        try {
            commentService.doSupport(id);
        } catch (ZhydCommentException e) {
            return ResultUtil.error(e.getMessage());
        }
        return ResultUtil.success("");
    }

@RequestParam
从request请求中接收参数
http://localhost:8080/springboot/0001?param1=1&param2=2

    @PostMapping("/springboot/{id}")
    @BussinessLog(value = "点赞评论{1}", platform = PlatformEnum.WEB)
    public ResponseVO doSupport(@PathVariable("id") Long id,
                            @RequestParam(value="param1", required=true) String param1,
                            @RequestParam(value="param2", required=false) String param2) {
        //........
        return ResultUtil.success("");
    }

 

@RequestHeader、@CookieValue、@ReuqestBody

待补充。。。。。。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值