非WEB工程怎麼在main方法中載入spring容器
阿新 • • 發佈:2019-01-01
很多非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(); }