1.先上代码
第一种

@Component
public class TestUtil {

	private static RemoteSysUserService sysUserService;

	private TestUtil(RemoteSysUserService remoteSysUserService){
		sysUserService = remoteSysUserService;
	}

	public static void sout(){
		System.out.println("remoteSysUserService:"+sysUserService);
	}
}

第二种:

@Component
public class TestUtil {

	@Autowired
	private RemoteSysUserService remoteSysUserService;

	private static RemoteSysUserService sysUserService;

	@PostConstruct
	public void init(){
		sysUserService = remoteSysUserService;
	}

	public static void sout(){
		System.out.println("remoteSysUserService:"+sysUserService);
	}
}

网上的方法大多数是第二种。
分析第二种:只需要加上@Component注解就可以了,在springboot单体工程中就可以保证被扫描到并注册到ioc容器中。但是我们为何又定义了一个静态的成员变量呢?因为工具类中的方法都是静态方法,不能直接引用非静态的成员变量。所以定义了一个静态成员变量。
@PostConstruct注解
@PostConstruct注解是由java提供的,但spring实现了该注解。主要在bean创建完成并且属性赋值完成之后执行一些初始化工作。@PostConstruct注解被用来修饰一个非静态的void()方法。被@PostConstruct注解修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。被@PostConstruct注解修饰的方法通常在构造函数之后,init()方法之前执行。
通常我们是会在Spring框架中使用到@PostConstruct注解的,该注解的方法在整个bean初始化中的执行顺序如下:
Constructor(构造方法)→@Autowired(依赖注入)→@PostConstruct(注释的方法)

以上是在springboot单体服务中的应用,但如果是微服务的工具类,这样还可以吗?
答案是No!如果在别的工程引用了该工具类,是无法被注册到ioc容器中的。why?
我们知道,@SpringCloudApplication注解底层包含了@SpringBootApplication注解,@SpringBootApplication注解底层包含了@ComponentScan
所以我们自定义的bean是通过@ComponentScan注解扫描 并注册到ioc容器中的,而此处引用的工具类是其他工程的,相当于是jar包,那jar包中的bean组件该如何被加载呢?
@SpringBootApplication注解底层包含@EnableAutoConfiguration,该注解会扫描整个工程中所有的META-INF/spring.factories文件,包括jar包里面的,然后把他们注册到ioc容器中。故而我们可以借助spring.factories来把工具类注册进来。在resources目录下,建立META-INF文件夹,创建spring.factories文件,添加如下内容。然后@Componnent注解可以去掉了,在微服务中想要把自己的类注册到ioc容器中,可以使用这种方法。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.ccb.smart.common.security.util.TestUtil