MVC 注解

常用注解

名称 作用
@Configuration
@ComponentScan
@Bean the method name annotated with @Bean work as bean ID and it creates and returns actual bean
@Controller
@Resource
@Autowired
@Value @Value({shiro.globalSessionTimeout:24*3600L}) Spring3 提供, PropertyPlaceHolderConfigurer、SpEL

@Autowired 与 @Resource 区别

  1. @Autowired 默认是按照类型注入的, 如果需要按照名称注入, 需要与@Qulifier一起使用, 由Spring提供. 此时Bean生命类型要和成员类型必须一致

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory){
     ...
    }
    
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;
    
  2. @Resource 默认按照名称来装配注入, 只有当找不到名称匹配的Bean, 才会按照类型来装配注入, 由J2EE提供.

    可以通过name属性来指定Bean的名称. 如果没有指定name的属性, 当注解标注在字段上, 即默认取字段的名称作为Bean名称寻找依赖对象.

    @Bean
    public StringRedisTemplate redisTemplate(RedisConnectionFactory factory){
    ...
    }
    
    @Resource
    private RedisTemplate redisTemplate;
    

    此时@Bean声明的类型既可以 RedisTemplate, 也可以是StringRedisTemplate

spring-boot-configuration