Spring 项目启动时执行

在spring中项目启动时执行可以将执行代码或者业务逻辑

可通过@Service、@Component、@Repository、@Controller。

将自动注册到Spring容器,不需要再在applicationContext.xml文件定义bean了


比如下面这个类:

方法一:

如果是静态资源的初始化 可在注入类中通过添加

static 块 来进行初始化 

简单例子:

@Component
public class VersionTool {
   public static String  VERSION = "";
   static {
      VERSION = "newTest";
   }
}

 

 

 

 项目启动时即可初始化参数;

方法二:

通过实现Spring 的 InitializingBean 

@Component
/**
 * /由于spring 注入的类属于懒加载,不被使用时不会实例化该对象。需要通过注解
 * @Lazy(value = false) 配置为非延时加载 org.springframework.context.annotation.Lazy;
 */
@Lazy(value = false)
@Slf4j
public class VersionTool implements InitializingBean {

   @Autowired
   private JedisPool jedisPool;

   @Override
   public void afterPropertiesSet() throws Exception {
      //访问db
      //初始化 字典数据
      //修改项目初始资源
      Jedis jedis = jedisPool.getResource();
      jedis.set("Token","newTest");
      log.info("jedis: {}",jedis.get("Token"));

   }
}

 

 

posted @ 2021-07-27 10:25  加了冰的才叫可乐  阅读(964)  评论(0编辑  收藏  举报