1.启动类main方法调用service
1.方式一
1.1 注入时候
如果不在启动类使用下述代码,请在代码所在类添加@Component注解,否则使用时会空指针。
注意:在@PostConstruct注解标注的方法中不能用getBean()方法获取bean达到给静态属性赋值的目的,因为getBean()在初始化之后才可获取到bean,@PostConstruct注解标注的方法属于初始化的一步。
1.2 调用时候
2.方式二
(service类要加@Service注解)
普通启动类:
package com.kaytune;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@MapperScan("com.kaytune.dao")
@SpringBootApplication
@EnableTransactionManagement
public class UmrEmployeesearchapiRedis {
public static void main(String[] args) {
SpringApplication.run(UmrEmployeesearchapiRedis.class, args);
}
}
在启动类获取Bean:
package com.kaytune.syncmembers2redis;
import com.kaytune.syncmembers2redis.schedulerservice.SyncBindingsSchedulerService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
@MapperScan("com.kaytune.syncmembers2redis.mapper")
public class Syncmembers2redisApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Syncmembers2redisApplication.class, args);
SyncBindingsSchedulerService sb = context.getBean(SyncBindingsSchedulerService.class);
sb.sync();
}
}
ApplicationContext context =SpringApplication.run(Syncmembers2redisApplication.class, args);
SyncBindingsSchedulerService sb
= context.getBean(SyncBindingsSchedulerService.class);
sb.sync();
2. 工具类调用dao
【在util工具类中有时候也会遇到注入不进去service或dao层导致空指针的情况,主要是因为注入的service、dao在static方法中调用导致的。也可以用大标题1中方法1解决-注意工具类要加@Component注解】
3.@Value注入配置文件属性到static修饰的属性
4.@Autowired注入Bean到static修饰的属性
当类加载器加载静态变量时,Spring上下文尚未加载。所以类加载器不会在bean中正确注入静态类,并且会失败。
解决方法有三种:
1.将类由@Component修饰,不采用static方法,属性就不用被static修饰了
略
2.将@Autowired加到构造方法上[所在类需要加@Component注解]
private static RedisTools redisTools;
private static DesUtil desUtil;
@Autowired
public RsaUtil(RedisTools redisTools, DesUtil desUtil) {
RsaUtil.redisTools = redisTools;
RsaUtil.desUtil = desUtil;
}
3.方式2类似“@Value注入配置文件属性到static修饰的属性”[所在类需要加@Component注解]
private static RedisTools redisTools;
private static DesUtil desUtil;
@Autowired
private RedisTools redisToolsTemp;
@Autowired
private DesUtil desUtilTemp;
@PostConstruct
public void beforeInit() {
redisTools = redisToolsTemp;
desUtil = desUtilTemp;
}