@Bean、@Component、 @Service、 @Repository 、 @Controller
@Bean:表示一个方法实例化、配置或者初始化一个Spring IoC容器管理的新对象。
@Data
@EnableConfigurationProperties
@Configuration
@ConfigurationProperties(prefix = "redis.cache")
public class RedisCacheConfig {
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
this.getRedisCacheConfigurationWithTtl(600),
this.getRedisCacheConfigurationMap()
);
}
}
@Component: 自动被component扫描。 表示被注解的类会自动被component扫描
@Component
public class RedisLimiterUtils {
@Resource
RedisTemplate<Object, Object> redisTemplate;
@Resource(name = "stringRedisTemplate")
ValueOperations<String, String> ops;
@Resource(name = "redisTemplate")
ValueOperations<Object, Object> objOps;
public void saveObject(String key, Object obj, long timeout) {
redisUtil.set(key, obj, timeout);
}
public void saveObject(String key, Object obj) {
redisUtil.set(key, obj);
}
public Object getObject(String key) {
return redisUtil.get(key);
}
public void removeObject(String key) {
redisUtil.del(key);
}
}
@Repository: 用于持久层,主要是数据库存储库。
@Repository
public interface NginxLogDao extends ElasticsearchRepository<NinxLogDocument, String> {
}
@Service: 表示被注解的类是位于业务层的业务component。
@Slf4j
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 保存用户验证码,和randomStr绑定
* @param deviceId
* 客户端生成
* @param imageCode
* 验证码信息
*/
@Override
public void saveImageCode(String deviceId, String imageCode) {
String text = imageCode.toLowerCase().toString();
redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
// redis info
connection.set(buildKey(deviceId).getBytes(), imageCode.getBytes());
connection.expire(buildKey(deviceId).getBytes(), 60*5);
connection.close();
return "";
}
});
}
/**
* 获取验证码
* @param deviceId
* 前端唯一标识/手机号
*/
@Override
public String getCode(String deviceId) {
String code = "" ;
try {
code = redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
// redis info
byte[] temp = "".getBytes();
temp = connection.get(buildKey(deviceId).getBytes()) ;
connection.close();
return new String(temp);
}
});
} catch (Exception e) {
throw new AuthenticationException("验证码不存在"){};
}
return code ;
}
/**
* 删除验证码
* @param deviceId
* 前端唯一标识/手机号
*/
@Override
public void remove(String deviceId) {
redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
// redis info
connection.del(buildKey(deviceId).getBytes());
connection.close();
return "";
}
});
}
/**
* 验证验证码
*/
@Override
public void validate(HttpServletRequest request) {
String deviceId = request.getParameter("deviceId");
if (StringUtils.isBlank(deviceId)) {
throw new AuthenticationException("请在请求参数中携带deviceId参数"){};
}
String code = this.getCode(deviceId);
String codeInRequest;
try {
codeInRequest = ServletRequestUtils.getStringParameter(request, "validCode");
} catch (ServletRequestBindingException e) {
throw new AuthenticationException ("获取验证码的值失败"){};
}
if (StringUtils.isBlank(codeInRequest)) {
throw new AuthenticationException ("请填写验证码"){};
}
if (code == null) {
throw new AuthenticationException ("验证码不存在或已过期"){};
}
if (!StringUtils.equalsIgnoreCase(code, codeInRequest)) {
throw new AuthenticationException ("验证码不正确"){};
}
this.remove(deviceId);
}
private String buildKey(String deviceId) {
return "DEFAULT_CODE_KEY:" + deviceId;
}
}
@Controller:表明被注解的类是控制component,主要用于展现层 。
@Controller
@Api(tags = "REDIS API")
@RequestMapping("/redis")
public class RedisController {
@Autowired
private RedisTemplate<String,Object> redisTemplate ;
@ResponseBody
@RequestMapping("/memoryInfo")
@LogAnnotation(module="auth-server",recordRequestParam=false)
public String getMemoryInfo() {
Map<String, Object> map = new HashMap<>();
Object o = redisTemplate.execute(new RedisCallback() {
@Override
public Object doInRedis(RedisConnection connection) throws DataAccessException {
return connection.info("memory").get("used_memory");
}
});
map.put("used_memory", o);
map.put("create_time", System.currentTimeMillis());
return JSON.toJSONString(map);
}
}
@Bean与@Component区别
@Component是 spring 2.5引入的,为了摆脱通过classpath扫描根据xml方式定义的bean的方式.
@Bean是spring 3.0 引入的,和 @Configuration一起工作,为了摆脱原先的xml和java config方式。
Spring管理Bean方式有两种,一种是注册Bean,一种装配Bean。
可以通过三种方式实现bean管理,一使用自动配置的方式、二使用JavaConfig的方式、三使用XML配置的方式。
@Component
@Data
public class User{
private String name = "tom";
}
@Bean 需要在配置类中使用,即类上需要加上@Component或者@Configuration注解, 通常加上@Configuration。 @Bean的用法在这里。
@Configuration
public class AppConfig {
@Bean
public TransferServiceImpl transferService() {
return new TransferServiceImpl();
}
}
@Autowired
private TransferService transferService;
@Component与@Service区别
目前基本没有区别。@Service是一种具体的@Component
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
String value() default "";
}
注解一览
@Autowired
@Qualifier
@Primary
@Resource
@Bean
@Component
@Service
@Repository
@Controller
网友评论