下面列出了org.springframework.context.annotation.EnableLoadTimeWeaving.AspectJWeaving#org.springframework.context.ConfigurableApplicationContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String[] args) throws UnknownHostException {
ConfigurableApplicationContext application = SpringApplication.run(MsgsServerApplication.class, args);
Environment env = application.getEnvironment();
log.info("\n----------------------------------------------------------\n\t" +
"应用 '{}' 运行成功! 访问连接:\n\t" +
"Swagger文档: \t\thttp://{}:{}/doc.html\n\t" +
"数据库监控: \t\thttp://{}:{}/druid\n" +
"----------------------------------------------------------",
env.getProperty("spring.application.name"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port")
);
}
@Test
public void testSendBynaryData() throws Exception {
try (ConfigurableApplicationContext context = SpringApplication.run(
SourceApplication.class, "--server.port=0",
"--spring.jmx.enabled=false")) {
MessageCollector collector = context.getBean(MessageCollector.class);
Source source = context.getBean(Source.class);
byte[] data = new byte[] { 0, 1, 2, 3 };
source.output()
.send(MessageBuilder.withPayload(data)
.setHeader(MessageHeaders.CONTENT_TYPE,
MimeTypeUtils.APPLICATION_OCTET_STREAM)
.build());
Message<byte[]> message = (Message<byte[]>) collector
.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
assertThat(
message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
.includes(MimeTypeUtils.APPLICATION_OCTET_STREAM));
assertThat(message.getPayload()).isEqualTo(data);
}
}
SpringBatchFlowRunner(StepBuilderFactory stepBuilderFactory,
JobBuilderFactory jobBuilderFactory,
ProjectsToRunFactory projectsToRunFactory, JobLauncher jobLauncher,
FlowRunnerTaskExecutorSupplier flowRunnerTaskExecutorSupplier,
ConfigurableApplicationContext context, ReleaserProperties releaserProperties,
BuildReportHandler reportHandler) {
this.stepBuilderFactory = stepBuilderFactory;
this.jobBuilderFactory = jobBuilderFactory;
this.projectsToRunFactory = projectsToRunFactory;
this.jobLauncher = jobLauncher;
this.flowRunnerTaskExecutorSupplier = flowRunnerTaskExecutorSupplier;
this.stepSkipper = new ConsoleInputStepSkipper(context, reportHandler);
this.releaserProperties = releaserProperties;
this.executorService = Executors.newFixedThreadPool(
this.releaserProperties.getMetaRelease().getReleaseGroupThreadCount());
}
public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(DemoApplication.class, args);
UserRepository userRepository = context.getBean(UserRepository.class);
AuthorityRepository authorityRepository = context.getBean(AuthorityRepository.class);
Authority adminAuthority = getOrGreateAuthority("ROLE_ADMIN", authorityRepository);
Authority basicAuthority = getOrGreateAuthority("ROLE_BASIC", authorityRepository);
User admin = new User("admin", "123456");
encodePassword(admin);
admin.getAuthorities().add(adminAuthority);
admin.getAuthorities().add(basicAuthority);
User test = new User("test", "test");
encodePassword(test);
test.getAuthorities().add(basicAuthority);
userRepository.save(admin);
userRepository.save(test);
}
@Test
public void testSimpleFunctionWithNativeProperty() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
TestChannelBinderConfiguration.getCompleteConfiguration(NoEnableBindingConfiguration.class))
.web(WebApplicationType.NONE)
.run("--spring.jmx.enabled=false", "--spring.cloud.function.definition=func")) {
InputDestination inputDestination = context.getBean(InputDestination.class);
OutputDestination outputDestination = context.getBean(OutputDestination.class);
Message<byte[]> inputMessage = MessageBuilder.withPayload("Hello".getBytes()).build();
inputDestination.send(inputMessage);
Message<byte[]> outputMessage = outputDestination.receive();
assertThat(outputMessage.getPayload()).isEqualTo("Hello".getBytes());
}
}
/**
* Resolve the set of merged {@code ApplicationContextInitializer} classes for the
* supplied list of {@code ContextConfigurationAttributes}.
*
* <p>Note that the {@link ContextConfiguration#inheritInitializers inheritInitializers}
* flag of {@link ContextConfiguration @ContextConfiguration} will be taken into
* consideration. Specifically, if the {@code inheritInitializers} flag is set to
* {@code true} for a given level in the class hierarchy represented by the provided
* configuration attributes, context initializer classes defined at the given level
* will be merged with those defined in higher levels of the class hierarchy.
*
* @param configAttributesList the list of configuration attributes to process; must
* not be {@code null} or <em>empty</em>; must be ordered <em>bottom-up</em>
* (i.e., as if we were traversing up the class hierarchy)
* @return the set of merged context initializer classes, including those from
* superclasses if appropriate (never {@code null})
* @since 3.2
*/
static Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> resolveInitializerClasses(
List<ContextConfigurationAttributes> configAttributesList) {
Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be empty");
final Set<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>> initializerClasses = //
new HashSet<Class<? extends ApplicationContextInitializer<? extends ConfigurableApplicationContext>>>();
for (ContextConfigurationAttributes configAttributes : configAttributesList) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("Processing context initializers for context configuration attributes %s",
configAttributes));
}
initializerClasses.addAll(Arrays.asList(configAttributes.getInitializers()));
if (!configAttributes.isInheritInitializers()) {
break;
}
}
return initializerClasses;
}
public static void main(String[] args) {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("factory.bean/factory-post-processor.xml");
BeanFactoryPostProcessor beanFactoryPostProcessor = (BeanFactoryPostProcessor) context.getBean("carPostProcessor");
beanFactoryPostProcessor.postProcessBeanFactory(context.getBeanFactory());
// 输出 :Car{maxSpeed=0, brand='*****', price=10000.0},敏感词被替换了
System.out.println(context.getBean("car"));
// 硬编码 后处理器执行时间
BeanFactoryPostProcessor hardCodeBeanFactoryPostProcessor = new HardCodeBeanFactoryPostProcessor();
context.addBeanFactoryPostProcessor(hardCodeBeanFactoryPostProcessor);
// 更新上下文
context.refresh();
// 输出 :
// Hard Code BeanFactory Post Processor execute time
// Car{maxSpeed=0, brand='*****', price=10000.0}
System.out.println(context.getBean("car"));
}
@Test
public void testWithExplicitBindingInstructionsOnlyDestination() {
System.clearProperty("spring.cloud.function.definition");
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(TestChannelBinderConfiguration
.getCompleteConfiguration(SplittableTypesConfiguration.class))
.web(WebApplicationType.NONE).run(
"--spring.cloud.function.definition=funcArrayOfMessages",
"--spring.cloud.stream.bindings.funcArrayOfMessages-in-0.destination=myInput",
"--spring.cloud.stream.bindings.funcArrayOfMessages-out-0.destination=myOutput",
"--spring.jmx.enabled=false")) {
InputDestination inputDestination = context.getBean(InputDestination.class);
OutputDestination outputDestination = context.getBean(OutputDestination.class);
Message<byte[]> inputMessage = MessageBuilder.withPayload("aa,bb,cc,dd".getBytes()).build();
inputDestination.send(inputMessage, "myInput");
assertThat(new String(outputDestination.receive(100, "myOutput").getPayload())).isEqualTo("aa");
assertThat(new String(outputDestination.receive(100, "myOutput").getPayload())).isEqualTo("bb");
assertThat(new String(outputDestination.receive(100, "myOutput").getPayload())).isEqualTo("cc");
assertThat(new String(outputDestination.receive(100, "myOutput").getPayload())).isEqualTo("dd");
assertThat(outputDestination.receive(100)).isNull();
}
}
@SuppressWarnings("unchecked")
private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
String className, ConfigurableApplicationContext wac) {
try {
Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
Class<?> initializerContextClass =
GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
throw new ApplicationContextException(String.format(
"Could not apply context initializer [%s] since its generic parameter [%s] " +
"is not assignable from the type of application context used by this " +
"framework servlet: [%s]", initializerClass.getName(), initializerContextClass.getName(),
wac.getClass().getName()));
}
return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(String.format("Could not load class [%s] specified " +
"via 'contextInitializerClasses' init-param", className), ex);
}
}
private void runTestAndVerifyHierarchies(Class<? extends FooTestCase> testClass, boolean isFooContextActive,
boolean isBarContextActive, boolean isBazContextActive) {
JUnitCore jUnitCore = new JUnitCore();
Result result = jUnitCore.run(testClass);
assertTrue("all tests passed", result.wasSuccessful());
assertThat(ContextHierarchyDirtiesContextTests.context, notNullValue());
ConfigurableApplicationContext bazContext = (ConfigurableApplicationContext) ContextHierarchyDirtiesContextTests.context;
assertEquals("baz", ContextHierarchyDirtiesContextTests.baz);
assertThat("bazContext#isActive()", bazContext.isActive(), is(isBazContextActive));
ConfigurableApplicationContext barContext = (ConfigurableApplicationContext) bazContext.getParent();
assertThat(barContext, notNullValue());
assertEquals("bar", ContextHierarchyDirtiesContextTests.bar);
assertThat("barContext#isActive()", barContext.isActive(), is(isBarContextActive));
ConfigurableApplicationContext fooContext = (ConfigurableApplicationContext) barContext.getParent();
assertThat(fooContext, notNullValue());
assertEquals("foo", ContextHierarchyDirtiesContextTests.foo);
assertThat("fooContext#isActive()", fooContext.isActive(), is(isFooContextActive));
}
private void addAncestorInitializer(SpringApplication application,
ConfigurableApplicationContext context) {
boolean installed = false;
for (ApplicationContextInitializer<?> initializer : application
.getInitializers()) {
if (initializer instanceof AncestorInitializer) {
installed = true;
// New parent
((AncestorInitializer) initializer).setParent(context);
}
}
if (!installed) {
application.addInitializers(new AncestorInitializer(context));
}
}
public static void main(String[] args) {
// 创建并且启动 BeanFactory 容器,
ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/META-INF/property-editors-context.xml");
// AbstractApplicationContext -> "conversionService" ConversionService Bean
// -> ConfigurableBeanFactory#setConversionService(ConversionService)
// -> AbstractAutowireCapableBeanFactory.instantiateBean
// -> AbstractBeanFactory#getConversionService ->
// BeanDefinition -> BeanWrapper -> 属性转换(数据来源:PropertyValues)->
// setPropertyValues(PropertyValues) -> TypeConverter#convertIfNecessnary
// TypeConverterDelegate#convertIfNecessnary -> PropertyEditor or ConversionService
User user = applicationContext.getBean("user", User.class);
System.out.println(user);
// 显示地关闭 Spring 应用上下文
applicationContext.close();
}
@Override
public void initialize(@NotNull ConfigurableApplicationContext configurableApplicationContext) {
String jdbcUrl = String.format("jdbc:postgresql://%s:%d/%s", postgres.getContainerIpAddress(),
postgres.getMappedPort(5432), "postgres");
TestPropertyValues values = TestPropertyValues.of(
"postgres.host=" + postgres.getContainerIpAddress(),
"postgres.port=" + postgres.getMappedPort(5432),
"postgres.url=" + jdbcUrl,
"postgres.database-name=postgres",
"spring.application.name=user-service",
"spring.datasource.data-username=postgres",
"spring.datasource.data-password=password",
"spring.datasource.url=" + jdbcUrl,
"eureka.client.enabled=false");
values.applyTo(configurableApplicationContext);
}
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
MutablePropertySources propertySources = environment.getPropertySources();
String[] defaultKeys = { "password", "secret", "key", "token", ".*credentials.*", "vcap_services" };
Set<String> propertiesToSanitize = Stream.of(defaultKeys).collect(Collectors.toSet());
PropertySource<?> bootstrapProperties = propertySources.get(BOOTSTRAP_PROPERTY_SOURCE_NAME);
Set<PropertySource<?>> bootstrapNestedPropertySources = new HashSet<>();
Set<PropertySource<?>> configServiceNestedPropertySources = new HashSet<>();
if (bootstrapProperties != null && bootstrapProperties instanceof CompositePropertySource) {
bootstrapNestedPropertySources.addAll(((CompositePropertySource) bootstrapProperties).getPropertySources());
}
for (PropertySource<?> nestedProperty : bootstrapNestedPropertySources) {
if (nestedProperty.getName().equals(CONFIG_SERVICE_PROPERTY_SOURCE_NAME)) {
configServiceNestedPropertySources
.addAll(((CompositePropertySource) nestedProperty).getPropertySources());
}
}
Stream<String> vaultKeyNameStream = configServiceNestedPropertySources.stream()
.filter(ps -> ps instanceof EnumerablePropertySource)
.filter(ps -> ps.getName().startsWith(VAULT_PROPERTY_PATTERN)
|| ps.getName().startsWith(CREDHUB_PROPERTY_PATTERN))
.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::<String>stream);
propertiesToSanitize.addAll(vaultKeyNameStream.collect(Collectors.toSet()));
PropertiesPropertySource envKeysToSanitize = new PropertiesPropertySource(SANITIZE_ENV_KEY,
mergeClientProperties(propertySources, propertiesToSanitize));
environment.getPropertySources().addFirst(envKeysToSanitize);
applicationContext.setEnvironment(environment);
}
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
TestPropertyValues.of(
"spring.datasource.url=" + postgreSQLContainer.getJdbcUrl(),
"spring.datasource.username=" + postgreSQLContainer.getUsername(),
"spring.datasource.password=" + postgreSQLContainer.getPassword()
).applyTo(configurableApplicationContext.getEnvironment());
}
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
try {
Resource resource = applicationContext.getResource("classpath:application.yml");
YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
List<PropertySource<?>> yamlTestProperties =
sourceLoader.load("yamlTestProperties", resource);
for (PropertySource<?> ps : yamlTestProperties) {
applicationContext.getEnvironment().getPropertySources().addLast(ps);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(final String[] args) {
try (final ConfigurableApplicationContext context = SpringApplication.run(SpringDataITest.class, args)) {
final UserRepository userRepository = context.getBean(UserRepository.class);
userRepository.save(new User());
userRepository.findAll();
TestUtil.checkSpan(new ComponentSpanCount("java-jdbc", 5));
}
}
@Test
public void registerUnregisterSingleContext() throws MalformedObjectNameException {
this.environment.setProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME, this.name.getMethodName());
ConfigurableApplicationContext context = createApplicationContext("app");
assertEquals(0, searchLiveBeansViewMeans().size());
LiveBeansView.registerApplicationContext(context);
assertSingleLiveBeansViewMbean("app");
LiveBeansView.unregisterApplicationContext(context);
assertEquals(0, searchLiveBeansViewMeans().size());
}
@Test
public void reverseEndpoint() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class,
PropertyPlaceholderAutoConfiguration.class)
.properties("websocket.uri:ws://localhost:" + this.port + "/ws/reverse")
.run("--spring.main.web-application-type=none");
long count = context.getBean(ClientConfiguration.class).latch.getCount();
AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload;
context.close();
assertThat(count).isEqualTo(0);
assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH");
}
@Test
public void registerUnregisterSingleContext() throws MalformedObjectNameException {
this.environment.setProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME, this.name.getMethodName());
ConfigurableApplicationContext context = createApplicationContext("app");
assertEquals(0, searchLiveBeansViewMeans().size());
LiveBeansView.registerApplicationContext(context);
assertSingleLiveBeansViewMbean("app");
LiveBeansView.unregisterApplicationContext(context);
assertEquals(0, searchLiveBeansViewMeans().size());
}
@Override
@Test
public void customConfiguration() {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
EnableJmsCustomConfig.class, CustomBean.class);
testCustomConfiguration(context);
}
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);
basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);
String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
// Actually scan for bean definitions and register them.
ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);
Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);
registerComponents(parserContext.getReaderContext(), beanDefinitions, element);
return null;
}
@Test
public void testInputOutputArgs() throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(
TestInputOutputArgs.class, "--server.port=0",
"--spring.cloud.stream.bindings.output.contentType=text/plain",
"--spring.jmx.enabled=false");
sendMessageAndValidate(context);
}
@AfterClass
public static void clean() {
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) webApp.getParent();
parent.close();
parentContext.close();
webApp.close();
}
/**
* Refresh this servlet's application context, as well as the
* dependent state of the servlet.
* @see #getWebApplicationContext()
* @see org.springframework.context.ConfigurableApplicationContext#refresh()
*/
public void refresh() {
WebApplicationContext wac = getWebApplicationContext();
if (!(wac instanceof ConfigurableApplicationContext)) {
throw new IllegalStateException("WebApplicationContext does not support refresh: " + wac);
}
((ConfigurableApplicationContext) wac).refresh();
}
private void receiveAndValidateFoo(ConfigurableApplicationContext context) {
Map<String, Object> senderProps = KafkaTestUtils.producerProps(embeddedKafka);
DefaultKafkaProducerFactory<Integer, String> pf = new DefaultKafkaProducerFactory<>(
senderProps);
KafkaTemplate<Integer, String> template = new KafkaTemplate<>(pf, true);
template.setDefaultTopic("foos");
template.sendDefault("{\"id\":\"123\"}");
ConsumerRecord<String, String> cr = KafkaTestUtils.getSingleRecord(consumer,
"counts-id");
assertThat(cr.value().contains("Count for product with ID 123: 1")).isTrue();
ProductCountApplication.Foo foo = context
.getBean(ProductCountApplication.Foo.class);
assertThat(foo.getProductStock(123).equals(1L));
// perform assertions on HostInfo related methods in InteractiveQueryService
InteractiveQueryService interactiveQueryService = context
.getBean(InteractiveQueryService.class);
HostInfo currentHostInfo = interactiveQueryService.getCurrentHostInfo();
assertThat(currentHostInfo.host() + ":" + currentHostInfo.port())
.isEqualTo(embeddedKafka.getBrokersAsString());
HostInfo hostInfo = interactiveQueryService.getHostInfo("prod-id-count-store",
123, new IntegerSerializer());
assertThat(hostInfo.host() + ":" + hostInfo.port())
.isEqualTo(embeddedKafka.getBrokersAsString());
HostInfo hostInfoFoo = interactiveQueryService
.getHostInfo("prod-id-count-store-foo", 123, new IntegerSerializer());
assertThat(hostInfoFoo).isNull();
final List<HostInfo> hostInfos = interactiveQueryService.getAllHostsInfo("prod-id-count-store");
assertThat(hostInfos.size()).isEqualTo(1);
final HostInfo hostInfo1 = hostInfos.get(0);
assertThat(hostInfo1.host() + ":" + hostInfo1.port())
.isEqualTo(embeddedKafka.getBrokersAsString());
}
@Test
public void testBeanScope() {
ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring/test-config-02.xml");
SimpleBean sb01 = ctx.getBean("simpleBean3", SimpleBean.class);
SimpleBean sb02 = ctx.getBean("simpleBean3", SimpleBean.class);
assertNotEquals(sb01, sb02);
ctx.close();
}
public AbstractSpringCloudRegistry(URL url, DiscoveryClient discoveryClient,
DubboServiceMetadataRepository dubboServiceMetadataRepository,
DubboMetadataServiceProxy dubboMetadataConfigServiceProxy,
JSONUtils jsonUtils, DubboGenericServiceFactory dubboGenericServiceFactory,
ConfigurableApplicationContext applicationContext) {
super(url);
this.servicesLookupInterval = url
.getParameter(SERVICES_LOOKUP_INTERVAL_PARAM_NAME, 60L);
this.discoveryClient = discoveryClient;
this.repository = dubboServiceMetadataRepository;
this.dubboMetadataConfigServiceProxy = dubboMetadataConfigServiceProxy;
this.jsonUtils = jsonUtils;
this.dubboGenericServiceFactory = dubboGenericServiceFactory;
this.applicationContext = applicationContext;
}
@Override
public void setApplicationContext(@NonNull ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
ELContext.setApplicationContext(applicationContext);
if (applicationContext instanceof ConfigurableApplicationContext) {
ApplicationContextHolder.environment.setConfigurableEnvironment(((ConfigurableApplicationContext) applicationContext).getEnvironment());
}
}
/**
* Fully initializeSmartModules Gemini as a normal start
*/
public static ConfigurableApplicationContext initializeGemini(Class... classes) {
ConfigurableApplicationContext context = startSpring(classes);
Gemini gemini = context.getBean(Gemini.class);
gemini.init();
return context;
}