一般调用spring注册服务都是mvn经过@Controller和@RequestMapping作为入口调用,而通过socket或netty是没法调用直接调用spring注册的服务
因此我们需要使用@PostConstruct注解来解决java原生直接调用spring注册的服务
先是使用@Component把服务注册到spring容器中,然后通过@PostConstruct (java原生注解)来init,最后就可以调用spring容器里面的服务了
详细如下:
package com.juebin.service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class NettyService {
private static NettyService nettyService;
@Autowired
private RedisTemplate<String,Object> redisTemplate;
@PostConstruct
public void init(){
nettyService = this;
nettyService.redisTemplate = this.redisTemplate;
}
public static void redisNetty(String date) {
nettyService.redisTemplate.opsForList().rightPush(dateToStr(), date);
nettyService.redisTemplate.expire(dateToStr(), 7, TimeUnit.HOURS);
}
}