非WEB工程怎么在main方法中加载spring容器

本文介绍两种启动Spring容器的方法:配置文件形式和注解形式。配置文件形式通过指定多个配置文件路径加载Spring容器并实例化UserService类;注解形式则通过注册配置类来初始化容器,并获取Student实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很多非WEB工程想引入spring的支持,就需要通过一个main方法启动加载spring容器

1.配置文件形式

//加载spring容器,并得到类的实例,下面配置文件是放在src/spring下面
public static void main(String[] args) {

//所有配置文件
args = new String[] {
"classpath:spring/spring-servlet.xml",
"classpath:spring/ApplicationContext.xml",
"classpath:spring/mybatis-config.xml",
};
ApplicationContext actx = new ClassPathXmlApplicationContext(args);

//得到类的实例
UserService userService = (UserService) actx.getBean("userService");

//调用类的方法
userService.deleteUser(2);
}



2.注解形式


public static void main( String[] args ) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.getEnvironment().setActiveProfiles("prod"); // 先将激活的Profile设置为prod
    ctx.register(Config.class, DevConfig.class, ProdConfig.class); // 后置注册Bean配置类,不然为报Bean未定义的错误
    ctx.refresh(); // 刷新容器
    Student student = ctx.getBean(Student.class);
    System.out.println(student.getName());

    ctx.close();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值