栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot项目启动时让方法自动执行

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot项目启动时让方法自动执行

1.实现CommandLineRunner接口
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
 
    
    @Override
    public void run(String... args) throws Exception {
        System.out.println("加载XXX...");
    }
 }

(其实直接在main方法里写也不是执行不了) 如果只是简单的一些语句,写在main中可能会方便一些但如果需要调用spring容器中的对象可能会要吃瘪,因为main方法是static的,而获取ioc对象不能使用static直接获取(会报错)

当调用@AutoWired获得ioc容器中的对象时

@Autowired
private static TestService testService;
Exception in thread "main" java.lang.NullPointerException

当调用@Resource获得ioc容器中的对象时

@Resource
private static TestService testService;
Caused by: java.lang.IllegalStateException: @Resource annotation is not supported on static fields


 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/760591.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号