Spring方式初始化方法

1第一种:实现ApplicationListener<ContextRefreshedEvent>接口 2 3package bdc.base; 4 5import java.util.HashMap; 6import java.util.List; 7import java.util.Map; 8 9import javax.annotation.Resource; 10 11import org.springframework.context.ApplicationListener; 12import org.springframework.context.event.ContextRefreshedEvent; 13 14import bdc.ws.dao.CommonDao; 15import bdc.ws.entity.RsaKey; 16//@Component 使用这个注解或者采用bean注入<bean id="afterSpringBegin" class="bdc.base.AfterSpringBegin"></bean> 17public class AfterSpringBegin implements 18 ApplicationListener<ContextRefreshedEvent> { 19 20 @Resource 21 private CommonDao commonDao; 22 public static final Map<String, RsaKey> KEY_RSA = new HashMap<String, RsaKey>(); 23 24 @Override 25 public void onApplicationEvent(ContextRefreshedEvent event) { 26 27 if (event.getApplicationContext().getParent() == null) { 28 try { 29 List<RsaKey> selectAllRsaKey = commonDao.selectAllRsaKey(); 30 for (int i = 0; i < selectAllRsaKey.size(); i++) { 31 KEY_RSA.put(selectAllRsaKey.get(i).getUserOrg(),selectAllRsaKey.get(i)); 32 } 33 } catch (Exception e) { 34 e.printStackTrace(); 35 } 36 } 37 } 38 39} 40 41第二种使用@PostConstruct注解 42@Component 43public class TuneNetInterface { 44 private static Client client; 45 private static QName opName; 46 @Value("${WebUrl}") 47 private String WebUrl; 48 @Value("${operation}") 49 private String operation; 50 51 @PostConstruct 52 public void init() {  //以下为具体逻辑 53 JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory 54 .newInstance(BusFactory.newInstance().createBus()); 55 client = factory.createClient(WebUrl); 56 Endpoint endpoint = client.getEndpoint(); 57 opName = new QName(endpoint.getService().getName().getNamespaceURI(), 58 operation); 59 BindingInfo bindingInfo = endpoint.getEndpointInfo().getBinding(); 60 if (bindingInfo.getOperation(opName) == null) { 61 for (BindingOperationInfo operationInfo : bindingInfo.getOperations()) { 62 if (operation.equals(operationInfo.getName().getLocalPart())) { 63 opName = operationInfo.getName(); 64 break; 65 } 66 } 67 } 68 69 } 70 71 public static Object[] request(String content) throws Exception { 72 return client.invoke(opName, content); 73 } 74 75}

第三种:使用@Configuration注解

1package com.dxz.demo.configuration; 2 3import org.springframework.context.annotation.Bean; 4import org.springframework.context.annotation.ComponentScan; 5import org.springframework.context.annotation.Configuration; 6import org.springframework.context.annotation.Scope; 7 8@Configuration 9//添加自动扫描注解,basePackages为TestBean包路径 10@ComponentScan(basePackages = "com.dxz.demo.configuration") 11public class TestConfiguration { 12 public TestConfiguration() { 13 System.out.println("TestConfiguration容器启动初始化。。。"); 14 } 15 16 /*// @Bean注解注册bean,同时可以指定初始化和销毁方法 17 // @Bean(name="testNean",initMethod="start",destroyMethod="cleanUp") 18 @Bean 19 @Scope("prototype") 20 public TestBean testBean() { 21 return new TestBean(); 22 }*/ 23} 24 25从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。 26 27注意:@Configuration注解的配置类有如下要求: 28 29@Configuration不可以是final类型; 30@Configuration不可以是匿名类; 31嵌套的configuration必须是静态类。 32一、用@Configuration加载spring 331.1、@Configuration配置spring并启动spring容器 341.2、@Configuration启动容器+@Bean注册Bean 351.3、@Configuration启动容器+@Component注册Bean 361.4、使用 AnnotationConfigApplicationContext 注册 AppContext 类的两种方法 371.5、配置Web应用程序(web.xml中配置AnnotationConfigApplicationContext) 38 39二、组合多个配置类 402.1、在@configuration中引入spring的xml配置文件 412.2、在@configuration中引入其它注解配置 422.3、@configuration嵌套(嵌套的Configuration必须是静态类) 43三、@EnableXXX注解 44四、@Profile逻辑组配置 45五、使用外部变量 46 47一、@Configuation加载Spring方法 481.1、@Configuration配置spring并启动spring容器 49@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans>,作用为:配置spring容器(应用上下文) 50 51复制代码 52package com.dxz.demo.configuration; 53 54import org.springframework.context.annotation.Configuration; 55 56@Configuration 57public class TestConfiguration { 58 public TestConfiguration() { 59 System.out.println("TestConfiguration容器启动初始化。。。"); 60 } 61} 62复制代码 63相当于: 64 65复制代码 66<?xml version="1.0" encoding="UTF-8"?> 67<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 68 xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" 69 xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" 70 xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" 71 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 72 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd 73 http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd 74 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd 75 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 76 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd 77 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false"> 78 79 80</beans> 81复制代码 82主方法进行测试: 83 84复制代码 85package com.dxz.demo.configuration; 86 87import org.springframework.context.ApplicationContext; 88import org.springframework.context.annotation.AnnotationConfigApplicationContext; 89 90public class TestMain { 91 public static void main(String[] args) { 92 93 // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext 94 ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class); 95 96 // 如果加载spring-context.xml文件: 97 // ApplicationContext context = new 98 // ClassPathXmlApplicationContext("spring-context.xml"); 99 } 100} 101复制代码 102从运行主方法结果可以看出,spring容器已经启动了: 103 104SpringBoot项目初始化1、 创建自定义类实现 CommandLineRunner接口,重写run()方法。springboot启动之后会默认去扫描所有实现了CommandLineRunner的类,并运行其run()方法。 105 106@Component 107@Order(2) //通过order值的大小来决定启动的顺序 108public class AskForLeave implements CommandLineRunner { 109 110 @Override 111 public void run(String... args) throws Exception { 112 askForLeave(); 113 } 114 115 public void askForLeave(){ 116 System.out.println("项目启动了,执行了方法"); 117 } 118}

2、创建自定义类实现ApplicationRunner 接口,重写run()方法。

1@Component 2@Order(3) 3public class Hello implements ApplicationRunner { 4 @Override 5 public void run(ApplicationArguments args) throws Exception { 6 7 hello(); 8 } 9 10 public void hello(){ 11 System.out.println("项目又启动了,这次使用的是:继承 ApplicationRunner"); 12 } 13}

关于二者的区别:

其实并没有什么区别,如果想获取更加详细的参数的时候,可以选择使用ApplicationRunner接口。其参数类型为:ApplicationArguments 。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )