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

来源:互联网 发布:c 语言整型常量 编辑:程序博客网 时间:2024/06/04 23:27

很多非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();}


阅读全文
0 0
原创粉丝点击