repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/Box.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/Box.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.api; public interface Box { String getName(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/MethodCallback.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/MethodCallback.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.api; public interface MethodCallback { void oninvoke1(String request); void onreturn1(String response, String request); void onthrow1(Throwable ex, String request); void oninvoke2(String request); void onreturn2(String response, String request); void onthrow2(Throwable ex, String request); String getOnInvoke1(); String getOnReturn1(); String getOnThrow1(); String getOnInvoke2(); String getOnReturn2(); String getOnThrow2(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/ProvidedByDemoService2.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/ProvidedByDemoService2.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.api; /** * DemoService */ public interface ProvidedByDemoService2 { String sayName(String name); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/DemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.api; public interface DemoService { String sayName(String name); Box getBox(); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/DemoServiceSon.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/DemoServiceSon.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.api; /** * DemoService */ public interface DemoServiceSon extends DemoService { // no methods }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/ProvidedByDemoService1.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/ProvidedByDemoService1.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.api; import org.apache.dubbo.config.annotation.ProvidedBy; /** * DemoService */ @ProvidedBy(name = "provided-demo-service-interface") public interface ProvidedByDemoService1 { String sayName(String name); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/SpringControllerService.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/SpringControllerService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.api; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/controller") public class SpringControllerService { @GetMapping("/sayHello") public String sayHello(String say) { return say; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/ProvidedByDemoService3.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/ProvidedByDemoService3.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.api; import org.apache.dubbo.config.annotation.ProvidedBy; /** * DemoService */ @ProvidedBy(name = {"provided-demo-service-interface1", "provided-demo-service-interface2"}) public interface ProvidedByDemoService3 { String sayName(String name); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/HelloService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.api; public interface HelloService { String sayHello(String name); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer3/PropertySourcesInJavaConfigTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer3/PropertySourcesInJavaConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.propertyconfigurer.consumer3; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.propertyconfigurer.consumer.DemoBeanFactoryPostProcessor; import java.io.IOException; import java.net.InetSocketAddress; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.ClassPathResource; class PropertySourcesInJavaConfigTest { private static final String SCAN_PACKAGE_NAME = "org.apache.dubbo.config.spring.propertyconfigurer.consumer3.notexist"; private static final String PACKAGE_PATH = "/org/apache/dubbo/config/spring/propertyconfigurer/consumer3"; private static final String PROVIDER_CONFIG_PATH = "org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml"; @BeforeEach public void setUp() throws Exception { DubboBootstrap.reset(); } @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); } @BeforeEach public void beforeTest() { DubboBootstrap.reset(); } @Test void testImportPropertySource() { ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(PROVIDER_CONFIG_PATH); try { providerContext.start(); // Resolve placeholder by import property sources AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( ConsumerConfiguration.class, ImportPropertyConfiguration.class); try { // expect auto create PropertySourcesPlaceholderConfigurer bean String[] beanNames = context.getBeanNamesForType(PropertySourcesPlaceholderConfigurer.class); Assertions.assertEquals(1, beanNames.length); Assertions.assertEquals(PropertySourcesPlaceholderConfigurer.class.getName(), beanNames[0]); HelloService service = (HelloService) context.getBean("demoService"); String result = service.sayHello("world"); Assertions.assertEquals( "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); } finally { context.close(); } } finally { providerContext.close(); } } @Test void testCustomPropertySourceBean() { ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(PROVIDER_CONFIG_PATH); try { providerContext.start(); // Resolve placeholder by custom PropertySourcesPlaceholderConfigurer bean AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( ConsumerConfiguration.class, PropertyBeanConfiguration.class); try { // expect using custom PropertySourcesPlaceholderConfigurer bean String[] beanNames = context.getBeanNamesForType(PropertySourcesPlaceholderConfigurer.class); Assertions.assertEquals(1, beanNames.length); Assertions.assertEquals("myPropertySourcesPlaceholderConfigurer", beanNames[0]); HelloService service = (HelloService) context.getBean("demoService"); String result = service.sayHello("world"); Assertions.assertEquals( "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); } finally { context.close(); } } finally { providerContext.close(); } } @Configuration @EnableDubbo(scanBasePackages = SCAN_PACKAGE_NAME) @ComponentScan(value = {SCAN_PACKAGE_NAME}) @ImportResource("classpath:" + PACKAGE_PATH + "/dubbo-consumer.xml") static class ConsumerConfiguration { @Bean public DemoBeanFactoryPostProcessor bizBeanFactoryPostProcessor(HelloService service) { return new DemoBeanFactoryPostProcessor(service); } } @Configuration @PropertySource("classpath:" + PACKAGE_PATH + "/app.properties") static class ImportPropertyConfiguration {} @Configuration static class PropertyBeanConfiguration { @Bean public MyPropertySourcesPlaceholderConfigurer myPropertySourcesPlaceholderConfigurer() { MyPropertySourcesPlaceholderConfigurer placeholderConfigurer = new MyPropertySourcesPlaceholderConfigurer(); placeholderConfigurer.setLocation(new ClassPathResource(PACKAGE_PATH + "/app.properties")); return placeholderConfigurer; } } static class MyPropertySourcesPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer { @Override protected String convertProperty(String propertyName, String propertyValue) { // .. do something .. return propertyValue; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/HelloServiceImpl.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/provider/HelloServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.propertyconfigurer.provider; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.rpc.RpcContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HelloServiceImpl implements HelloService { private static final Logger logger = LoggerFactory.getLogger(HelloServiceImpl.class); @Override public String sayHello(String name) { logger.info("Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer2/PropertySourcesConfigurerTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer2/PropertySourcesConfigurerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.propertyconfigurer.consumer2; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.propertyconfigurer.consumer.DemoBeanFactoryPostProcessor; import java.net.InetSocketAddress; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.support.ClassPathXmlApplicationContext; class PropertySourcesConfigurerTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Test void testEarlyInit() { ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext( "org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml"); try { providerContext.start(); // consumer app // Resolve placeholder by PropertySourcesPlaceholderConfigurer in dubbo-consumer.xml, without import // property source. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class); try { context.start(); HelloService service = (HelloService) context.getBean("demoService"); String result = service.sayHello("world"); Assertions.assertEquals( "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); } finally { context.close(); } } finally { providerContext.close(); } } @Configuration @EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.propertyconfigurer.consumer2") @ComponentScan(value = {"org.apache.dubbo.config.spring.propertyconfigurer.consumer2"}) @ImportResource("classpath:/org/apache/dubbo/config/spring/propertyconfigurer/consumer2/dubbo-consumer.xml") static class ConsumerConfiguration { @Bean public DemoBeanFactoryPostProcessor bizBeanFactoryPostProcessor(HelloService service) { return new DemoBeanFactoryPostProcessor(service); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer/PropertyConfigurerTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer/PropertyConfigurerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.propertyconfigurer.consumer; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import java.net.InetSocketAddress; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.support.ClassPathXmlApplicationContext; class PropertyConfigurerTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Test void testEarlyInit() { ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext( "org/apache/dubbo/config/spring/propertyconfigurer/provider/dubbo-provider.xml"); try { providerContext.start(); // Resolve placeholder by PropertyPlaceholderConfigurer in dubbo-consumer.xml, without import property // source. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class); context.start(); HelloService service = (HelloService) context.getBean("demoService"); String result = service.sayHello("world"); Assertions.assertEquals( "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); context.close(); } finally { providerContext.close(); } } @Configuration @EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.propertyconfigurer.consumer") @ComponentScan(value = {"org.apache.dubbo.config.spring.propertyconfigurer.consumer"}) @ImportResource("classpath:/org/apache/dubbo/config/spring/propertyconfigurer/consumer/dubbo-consumer.xml") static class ConsumerConfiguration { @Bean public DemoBeanFactoryPostProcessor bizBeanFactoryPostProcessor(HelloService service) { return new DemoBeanFactoryPostProcessor(service); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer/DemoBeanFactoryPostProcessor.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/propertyconfigurer/consumer/DemoBeanFactoryPostProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.propertyconfigurer.consumer; import org.apache.dubbo.config.spring.api.HelloService; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.core.PriorityOrdered; public class DemoBeanFactoryPostProcessor implements BeanFactoryPostProcessor, PriorityOrdered { private HelloService demoService; public DemoBeanFactoryPostProcessor(HelloService demoService) { this.demoService = demoService; } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (demoService == null) { throw new IllegalStateException("demoService is not injected"); } } /** * call before PropertyPlaceholderConfigurer */ @Override public int getOrder() { return HIGHEST_PRECEDENCE; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/ReferenceKeyTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/ReferenceKeyTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference; import org.apache.dubbo.config.annotation.Argument; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.SysProps; import org.apache.dubbo.config.spring.api.DemoService; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.api.ProvidedByDemoService1; import org.apache.dubbo.config.spring.api.ProvidedByDemoService2; import org.apache.dubbo.config.spring.api.ProvidedByDemoService3; import org.apache.dubbo.config.spring.impl.DemoServiceImpl; import org.apache.dubbo.config.spring.impl.HelloServiceImpl; import org.apache.dubbo.config.spring.util.AnnotationUtils; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.core.annotation.AnnotationAttributes; class ReferenceKeyTest { @BeforeEach protected void setUp() { DubboBootstrap.reset(); SysProps.clear(); SysProps.setProperty("dubbo.metrics.enabled", "false"); SysProps.setProperty("dubbo.metrics.protocol", "disabled"); } @AfterEach void tearDown() { DubboBootstrap.reset(); SysProps.clear(); } @Test void testReferenceKey() throws Exception { String helloService1 = getReferenceKey("helloService"); String helloService2 = getReferenceKey("helloService2"); String helloService3 = getReferenceKey("helloService3"); String helloService4 = getReferenceKey("helloService4"); Assertions.assertEquals( "ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(methods=[{name=sayHello, retries=0, timeout=100}])", helloService1); Assertions.assertEquals(helloService1, helloService2); Assertions.assertEquals( "ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(methods=[{arguments=[{callback=true, index=0}], name=sayHello, timeout=100}])", helloService3); Assertions.assertEquals(helloService3, helloService4); String helloServiceWithArray0 = getReferenceKey("helloServiceWithArray0"); String helloServiceWithArray1 = getReferenceKey("helloServiceWithArray1"); String helloServiceWithArray2 = getReferenceKey("helloServiceWithArray2"); String helloServiceWithMethod1 = getReferenceKey("helloServiceWithMethod1"); String helloServiceWithMethod2 = getReferenceKey("helloServiceWithMethod2"); String helloServiceWithArgument1 = getReferenceKey("helloServiceWithArgument1"); String helloServiceWithArgument2 = getReferenceKey("helloServiceWithArgument2"); Assertions.assertEquals( "ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],parameters={a=2, b=1})", helloServiceWithArray0); Assertions.assertNotEquals(helloServiceWithArray0, helloServiceWithArray1); Assertions.assertEquals( "ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],parameters={a=1, b=2})", helloServiceWithArray1); Assertions.assertEquals(helloServiceWithArray1, helloServiceWithArray2); Assertions.assertEquals( "ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],methods=[{name=sayHello, parameters={c=1, d=2}, timeout=100}],parameters={a=1, b=2})", helloServiceWithMethod1); Assertions.assertEquals(helloServiceWithMethod1, helloServiceWithMethod2); Assertions.assertEquals( "ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],methods=[{arguments=[{callback=true, type=String}, {type=int}], name=sayHello, timeout=100}],parameters={a=1, b=2})", helloServiceWithArgument1); Assertions.assertEquals(helloServiceWithArgument1, helloServiceWithArgument2); } @Test void testConfig() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration.class); context.start(); Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(2, referenceBeanMap.size()); Assertions.assertEquals( "ReferenceBean:demo/org.apache.dubbo.config.spring.api.DemoService:1.2.3(consumer=my-consumer,init=false,methods=[{arguments=[{callback=true, index=0}], name=sayName, parameters={access-token=my-token, b=2}, retries=0}],parameters={connec.timeout=1000},protocol=dubbo,registryIds=my-registry,scope=remote,timeout=1000,url=dubbo://127.0.0.1:20813)", referenceBeanMap.get("&demoService").getKey()); } @Test @Disabled("support multi reference config") public void testConfig2() { try { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration2.class); context.start(); Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.fail("Reference bean check failed"); } catch (BeansException e) { String msg = getStackTrace(e); Assertions.assertTrue( msg.contains( "Found multiple ReferenceConfigs with unique service name [demo/org.apache.dubbo.config.spring.api.DemoService:1.2.3]"), msg); // Assertions.assertTrue(msg.contains("Already exists another reference bean with the same bean // name and type but difference attributes"), msg); // Assertions.assertTrue(msg.contains("ConsumerConfiguration2.demoService"), msg); } } @Test void testConfig3() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration3.class); context.start(); Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(3, referenceBeanMap.size()); Assertions.assertNotNull(referenceBeanMap.get("&demoService#2")); ConsumerConfiguration3 consumerConfiguration3 = context.getBean(ConsumerConfiguration3.class); Assertions.assertEquals(consumerConfiguration3.demoService, consumerConfiguration3.helloService); } @Test void testConfig4() { AnnotationConfigApplicationContext context = null; try { context = new AnnotationConfigApplicationContext(ConsumerConfiguration4.class); context.start(); Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.fail("Reference bean check failed"); } catch (BeansException e) { String msg = getStackTrace(e); Assertions.assertTrue(msg.contains("Duplicate spring bean name: demoService"), msg); } finally { if (context != null) { context.close(); } } } @Test void testConfig5() { try { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration5.class); context.start(); Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.fail("Reference bean check failed"); } catch (BeansException e) { Assertions.assertTrue(getStackTrace(e).contains("Duplicate spring bean name: demoService")); } } @Test void testConfig6() { try { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConsumerConfiguration6.class); context.start(); Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.fail("Reference bean check failed"); } catch (BeansException e) { String checkString = "Already exists another bean definition with the same bean name [demoService], but cannot rename the reference bean name"; String msg = getStackTrace(e); Assertions.assertTrue(msg.contains(checkString), msg); Assertions.assertTrue(msg.contains("ConsumerConfiguration6.demoService"), msg); } } @Test void testConfig7() throws Exception { String fieldName1 = "providedByDemoService1"; String fieldName2 = "providedByDemoService2"; String fieldName3 = "providedByDemoServiceInterface"; String fieldName4 = "multiProvidedByDemoServiceInterface"; Map<String, Object> attributes1 = getReferenceAttributes(fieldName1); Map<String, Object> attributes2 = getReferenceAttributes(fieldName2); Map<String, Object> attributes3 = getReferenceAttributes(fieldName3); Map<String, Object> attributes4 = getReferenceAttributes(fieldName4); Assertions.assertEquals("provided-demo-service-interface", ((String[]) attributes1.get("providedBy"))[0]); Assertions.assertEquals("provided-demo-service1", ((String[]) attributes1.get("providedBy"))[1]); Assertions.assertEquals("provided-demo-service2", ((String[]) attributes2.get("providedBy"))[0]); Assertions.assertEquals("provided-demo-service-interface", ((String[]) attributes3.get("providedBy"))[0]); String[] serviceName4 = (String[]) attributes4.get("providedBy"); List<String> expectServices = new ArrayList<>(); expectServices.add("provided-demo-service-interface1"); expectServices.add("provided-demo-service-interface2"); Assertions.assertTrue(serviceName4.length == 2 && expectServices.contains(serviceName4[0]) && expectServices.contains(serviceName4[1])); Assertions.assertEquals("provided-demo-service-interface", ((String[]) attributes3.get("providedBy"))[0]); } private String getStackTrace(Throwable ex) { StringWriter stringWriter = new StringWriter(); ex.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } private String getReferenceKey(String fieldName) throws NoSuchFieldException { Field field = ReferenceConfiguration.class.getDeclaredField(fieldName); AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes(field, DubboReference.class, null, true); ReferenceBeanSupport.convertReferenceProps(attributes, field.getType()); return ReferenceBeanSupport.generateReferenceKey(attributes, null); } private Map<String, Object> getReferenceAttributes(String fieldName) throws NoSuchFieldException { Field field = ConsumerConfiguration7.class.getDeclaredField(fieldName); AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes(field, DubboReference.class, null, true); ReferenceBeanSupport.convertReferenceProps(attributes, field.getType()); return attributes; } static class ReferenceConfiguration { @DubboReference(methods = @Method(name = "sayHello", timeout = 100, retries = 0)) private HelloService helloService; @DubboReference(methods = @Method(timeout = 100, name = "sayHello", retries = 0)) private HelloService helloService2; @DubboReference( methods = @Method(name = "sayHello", timeout = 100, arguments = @Argument(index = 0, callback = true))) private HelloService helloService3; @DubboReference( methods = @Method(arguments = @Argument(callback = true, index = 0), name = "sayHello", timeout = 100)) private HelloService helloService4; // Instance 1 @DubboReference( check = false, parameters = {"a", "2", "b", "1"}, filter = {"echo"}) private HelloService helloServiceWithArray0; // Instance 2 @DubboReference( check = false, parameters = {"a=1", "b", "2"}, filter = {"echo"}) private HelloService helloServiceWithArray1; @DubboReference( parameters = {"b", "2", "a", "1"}, filter = {"echo"}, check = false) private HelloService helloServiceWithArray2; // Instance 3 @DubboReference( check = false, parameters = {"a", "1", "b", "2"}, filter = {"echo"}, methods = { @Method( parameters = {"d", "2", "c", "1"}, name = "sayHello", timeout = 100) }) private HelloService helloServiceWithMethod1; @DubboReference( parameters = {"b=2", "a=1"}, filter = {"echo"}, check = false, methods = { @Method( name = "sayHello", timeout = 100, parameters = {"c", "1", "d", "2"}) }) private HelloService helloServiceWithMethod2; // Instance 4 @DubboReference( parameters = {"a", "1", "b", "2"}, filter = {"echo"}, methods = { @Method( name = "sayHello", arguments = { @Argument(callback = true, type = "String"), @Argument(callback = false, type = "int") }, timeout = 100) }, check = false) private HelloService helloServiceWithArgument1; @DubboReference( check = false, filter = {"echo"}, parameters = {"b", "2", "a", "1"}, methods = { @Method( name = "sayHello", timeout = 100, arguments = { @Argument(callback = false, type = "int"), @Argument(callback = true, type = "String") }) }) private HelloService helloServiceWithArgument2; } @Configuration @ImportResource({ "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" }) static class ConsumerConfiguration { // both are reference beans, same as xml config @DubboReference( group = "demo", version = "1.2.3", consumer = "my-consumer", init = false, methods = { @Method( arguments = {@Argument(callback = true, index = 0)}, name = "sayName", parameters = {"access-token", "my-token", "b", "2"}, retries = 0) }, parameters = {"connec.timeout", "1000"}, protocol = "dubbo", registry = "my-registry", scope = "remote", timeout = 1000, url = "dubbo://127.0.0.1:20813") private DemoService demoService; } @Configuration @ImportResource({ "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" }) static class ConsumerConfiguration2 { // both are reference beans, same bean name and type, but difference attributes from xml config @DubboReference( group = "demo", version = "1.2.3", consumer = "my-consumer", init = false, scope = "local", timeout = 100) private DemoService demoService; } @Configuration @ImportResource({ "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" }) static class ConsumerConfiguration3 { // both are reference beans, same bean name but difference interface type @DubboReference( group = "demo", version = "1.2.4", consumer = "my-consumer", init = false, url = "dubbo://127.0.0.1:20813") private HelloService demoService; @Autowired private HelloService helloService; } @Configuration @ImportResource({ "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" }) static class ConsumerConfiguration4 { // not reference bean: same bean name and type @Bean public DemoService demoService() { return new DemoServiceImpl(); } } @Configuration @ImportResource({ "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" }) static class ConsumerConfiguration5 { // not reference bean: same bean name but difference type @Bean public HelloService demoService() { return new HelloServiceImpl(); } } @Configuration @ImportResource({ "classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml", "classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml" }) static class ConsumerConfiguration6 { // both are reference beans, same bean name but difference interface type, fixed bean name @DubboReference( id = "demoService", group = "demo", version = "1.2.3", consumer = "my-consumer", init = false, url = "dubbo://127.0.0.1:20813") private HelloService demoService; // @Autowired // private HelloService helloService; } @Configuration static class ConsumerConfiguration7 { // both are reference beans, same as xml config @DubboReference(providedBy = "provided-demo-service1") private ProvidedByDemoService1 providedByDemoService1; @DubboReference(providedBy = "provided-demo-service2") private ProvidedByDemoService2 providedByDemoService2; @DubboReference(providedBy = {"provided-demo-service3", "provided-demo-service4"}) private ProvidedByDemoService2 multiProvidedByDemoService; @DubboReference private ProvidedByDemoService1 providedByDemoServiceInterface; @DubboReference private ProvidedByDemoService3 multiProvidedByDemoServiceInterface; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/DubboConfigBeanInitializerTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/DubboConfigBeanInitializerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.DubboConfigBeanInitializer; import org.apache.dubbo.config.spring.context.annotation.provider.ProviderConfiguration; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.Import; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; /** * Tests for {@link org.apache.dubbo.config.spring.context.DubboConfigBeanInitializer} */ @ExtendWith(SpringExtension.class) @ContextConfiguration( classes = { DubboConfigBeanInitializerTest.class, DubboConfigBeanInitializerTest.AppConfiguration.class, }) @TestPropertySource(properties = {"dubbo.protocol.port=-1", "dubbo.registry.address=${zookeeper.connection.address}"}) @EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) class DubboConfigBeanInitializerTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Autowired private FooService fooService; @Autowired private ApplicationContext applicationContext; @Test void test() { Assertions.assertNotNull(fooService, "fooService is null"); Assertions.assertNotNull(fooService.helloService, "ooService.helloService is null"); // expect fooService is registered before dubbo config bean List<String> beanNames = Arrays.asList(applicationContext.getBeanDefinitionNames()); int fooServiceIndex = beanNames.indexOf("fooService"); int applicationConfigIndex = beanNames.indexOf("dubbo-demo-application"); int registryConfigIndex = beanNames.indexOf("my-registry"); int configInitializerIndex = beanNames.indexOf(DubboConfigBeanInitializer.BEAN_NAME); Assertions.assertTrue(fooServiceIndex < applicationConfigIndex); Assertions.assertTrue(fooServiceIndex < registryConfigIndex); Assertions.assertTrue(fooServiceIndex < configInitializerIndex); } @Configuration // Import BusinessConfig first, make sure FooService bean is register early, // expect dubbo config beans are initialized before FooService bean @Import({BusinessConfig.class, ConsumerConfig.class, ProviderConfiguration.class}) static class AppConfiguration {} @Configuration static class BusinessConfig { @Bean public FooService fooService(ApplicationContext applicationContext) { // Dubbo config beans should be initialized at DubboConfigInitializer, before init FooService bean Assertions.assertTrue(DubboBeanUtils.getModuleModel(applicationContext) .getDeployer() .isInitialized()); Assertions.assertTrue(DubboBeanUtils.getApplicationModel(applicationContext) .getDeployer() .isInitialized()); Assertions.assertTrue(DubboBootstrap.getInstance().isInitialized()); return new FooService(); } } @Configuration static class ConsumerConfig { @DubboReference private HelloService helloService; } static class FooService { @Autowired private HelloService helloService; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcalla/LocalCallReferenceAnnotationTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcalla/LocalCallReferenceAnnotationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference.localcalla; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.rpc.RpcContext; import java.net.InetSocketAddress; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @EnableDubbo @ExtendWith(SpringExtension.class) @PropertySource("classpath:/org/apache/dubbo/config/spring/reference/localcalla/local-call-config.properties") @ContextConfiguration( classes = {LocalCallReferenceAnnotationTest.class, LocalCallReferenceAnnotationTest.LocalCallConfiguration.class }) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class LocalCallReferenceAnnotationTest { @BeforeAll public static void setUp() { DubboBootstrap.reset(); } @AfterAll public static void tearDown() { DubboBootstrap.reset(); } @Autowired private HelloService helloService; @Autowired private ApplicationContext applicationContext; @Test void testLocalCall() { // see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke // InjvmInvoker set remote address to 127.0.0.1:0 String result = helloService.sayHello("world"); Assertions.assertEquals( "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); } @Configuration public static class LocalCallConfiguration { @DubboReference(injvm = true) private HelloService helloService; } @DubboService public static class AnotherLocalHelloServiceImpl implements HelloService { @Override public String sayHello(String name) { return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallmix/LocalCallReferenceMixTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallmix/LocalCallReferenceMixTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference.localcallmix; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.rpc.RpcContext; import java.net.InetSocketAddress; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @EnableDubbo @ExtendWith(SpringExtension.class) @PropertySource("classpath:/org/apache/dubbo/config/spring/reference/localcallmix/local-call-config.properties") @ContextConfiguration( classes = {LocalCallReferenceMixTest.class, LocalCallReferenceMixTest.LocalCallConfiguration.class}) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) @ImportResource("classpath:/org/apache/dubbo/config/spring/reference/localcallmix/local-call-consumer.xml") class LocalCallReferenceMixTest { @BeforeAll public static void setUp() { DubboBootstrap.reset(); } @AfterAll public static void tearDown() { DubboBootstrap.reset(); } @Autowired private HelloService helloService; @Autowired private ApplicationContext applicationContext; @Test void testLocalCall() { // see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke // InjvmInvoker set remote address to 127.0.0.1:0 String result = helloService.sayHello("world"); Assertions.assertEquals( "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); } @Configuration public static class LocalCallConfiguration { @DubboReference(injvm = true) private HelloService helloService; } @DubboService public static class AnotherLocalHelloServiceImpl implements HelloService { @Override public String sayHello(String name) { return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallam/LocalCallMultipleReferenceAnnotationsTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallam/LocalCallMultipleReferenceAnnotationsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference.localcallam; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.rpc.RpcContext; import java.net.InetSocketAddress; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @EnableDubbo @ExtendWith(SpringExtension.class) @PropertySource("classpath:/org/apache/dubbo/config/spring/reference/localcallam/local-call-config.properties") @ContextConfiguration( classes = { LocalCallMultipleReferenceAnnotationsTest.class, LocalCallMultipleReferenceAnnotationsTest.LocalCallConfiguration.class }) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class LocalCallMultipleReferenceAnnotationsTest { @BeforeAll public static void setUp() { DubboBootstrap.reset(); } @Autowired private HelloService helloService; @Autowired private HelloService demoHelloService; @Autowired private ApplicationContext applicationContext; @Test void testLocalCall() { // see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke // InjvmInvoker set remote address to 127.0.0.1:0 String result = helloService.sayHello("world"); Assertions.assertEquals( "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); String demoResult = demoHelloService.sayHello("world"); Assertions.assertEquals( "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), demoResult); Map<String, ReferenceBean> referenceBeanMap = applicationContext.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(2, referenceBeanMap.size()); Assertions.assertTrue(referenceBeanMap.containsKey("&helloService")); Assertions.assertTrue(referenceBeanMap.containsKey("&demoHelloService")); // helloService3 and demoHelloService share the same ReferenceConfig instance ReferenceBean helloService3ReferenceBean = applicationContext.getBean("&helloService3", ReferenceBean.class); ReferenceBean demoHelloServiceReferenceBean = applicationContext.getBean("&demoHelloService", ReferenceBean.class); Assertions.assertSame(helloService3ReferenceBean, demoHelloServiceReferenceBean); } @Configuration public static class LocalCallConfiguration { @DubboReference private HelloService helloService; @DubboReference(group = "demo", version = "2.0.0") private HelloService demoHelloService; @DubboReference(group = "${biz.group}", version = "${biz.version}") private HelloService helloService3; } @Configuration public static class LocalCallConfiguration2 { @DubboReference private HelloService helloService; @DubboReference(group = "${biz.group}", version = "2.0.0") private HelloService demoHelloService; } @Configuration public static class LocalCallConfiguration3 { @DubboReference(group = "foo") private HelloService demoHelloService; } @DubboService public static class AnotherLocalHelloServiceImpl implements HelloService { @Override public String sayHello(String name) { return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); } } @DubboService(group = "demo", version = "2.0.0") public static class DemoHelloServiceImpl implements HelloService { @Override public String sayHello(String name) { return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalHelloServiceImpl.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalHelloServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference.localcall; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.rpc.RpcContext; public class LocalHelloServiceImpl implements HelloService { @Override public String sayHello(String name) { return "Hello " + name + ", response from provider: " + RpcContext.getContext().getLocalAddress(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference.localcall; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; import java.net.InetSocketAddress; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @ExtendWith(SpringExtension.class) @ContextConfiguration( locations = { "classpath:/org/apache/dubbo/config/spring/reference/localcall/local-call-provider.xml", "classpath:/org/apache/dubbo/config/spring/reference/localcall/local-call-consumer.xml" }) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class LocalCallTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Autowired private HelloService helloService; @Autowired // @Qualifier("localHelloService") private HelloService localHelloService; @Test void testLocalCall() { // see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke // InjvmInvoker set remote address to 127.0.0.1:0 String result = helloService.sayHello("world"); Assertions.assertEquals( "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); // direct call local service, the remote address is null String originResult = localHelloService.sayHello("world"); Assertions.assertEquals("Hello world, response from provider: null", originResult); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest2.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest2.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference.localcall; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; import java.net.InetSocketAddress; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @ExtendWith(SpringExtension.class) @ContextConfiguration( locations = {"classpath:/org/apache/dubbo/config/spring/reference/localcall/local-call-provider.xml"}) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) public class LocalCallTest2 { @BeforeAll public static void setUp() { DubboBootstrap.reset(); } @AfterAll public static void tearDown() { DubboBootstrap.reset(); } @DubboReference private HelloService helloService; @Autowired private ApplicationContext applicationContext; @Test public void testLocalCall() { // see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke // InjvmInvoker set remote address to 127.0.0.1:0 String result = helloService.sayHello("world"); Assertions.assertEquals( "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/javaconfig/JavaConfigReferenceBeanTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/javaconfig/JavaConfigReferenceBeanTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference.javaconfig; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.SysProps; import org.apache.dubbo.config.spring.api.DemoService; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.impl.HelloServiceImpl; import org.apache.dubbo.config.spring.reference.ReferenceBeanBuilder; import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericService; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.List; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; class JavaConfigReferenceBeanTest { @BeforeEach public void setUp() { DubboBootstrap.reset(); SysProps.clear(); SysProps.setProperty("dubbo.metrics.enabled", "false"); SysProps.setProperty("dubbo.metrics.protocol", "disabled"); } @AfterEach public void tearDown() { DubboBootstrap.reset(); SysProps.clear(); } @Test void testAnnotationAtField() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CommonConfig.class, AnnotationAtFieldConfiguration.class); try { Map<String, HelloService> helloServiceMap = context.getBeansOfType(HelloService.class); Assertions.assertEquals(2, helloServiceMap.size()); Assertions.assertNotNull(helloServiceMap.get("helloService")); Assertions.assertNotNull(helloServiceMap.get("helloServiceImpl")); Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(1, referenceBeanMap.size()); ReferenceBean referenceBean = referenceBeanMap.get("&helloService"); Assertions.assertEquals("demo", referenceBean.getGroup()); Assertions.assertEquals(HelloService.class, referenceBean.getInterfaceClass()); Assertions.assertEquals(HelloService.class.getName(), referenceBean.getServiceInterface()); } finally { context.close(); } } @Test @Disabled("support multi reference config") public void testAnnotationAtField2() { AnnotationConfigApplicationContext context = null; try { context = new AnnotationConfigApplicationContext( CommonConfig.class, AnnotationAtFieldConfiguration.class, AnnotationAtFieldConfiguration2.class); Assertions.fail("Should not load duplicated @DubboReference fields"); } catch (Exception e) { String msg = getStackTrace(e); Assertions.assertTrue( msg.contains( "Found multiple ReferenceConfigs with unique service name [demo/org.apache.dubbo.config.spring.api.HelloService]"), msg); } finally { if (context != null) { context.close(); } } } @Test void testLazyProxy1() { AnnotationConfigApplicationContext context = null; try { context = new AnnotationConfigApplicationContext(CommonConfig.class, LazyProxyConfiguration1.class); HelloService helloServiceClient = context.getBean("helloServiceClient", HelloService.class); Assertions.assertNotNull(helloServiceClient); Assertions.assertInstanceOf(HelloService.class, helloServiceClient); Class<? extends HelloService> clientClass = helloServiceClient.getClass(); Assertions.assertFalse(Modifier.isFinal(clientClass.getModifiers())); Assertions.assertEquals("Hello, dubbo", helloServiceClient.sayHello("dubbo")); } finally { if (context != null) { context.close(); } } } @Test void testLazyProxy2() { AnnotationConfigApplicationContext context = null; try { context = new AnnotationConfigApplicationContext(CommonConfig.class, LazyProxyConfiguration2.class); HelloService helloServiceClient = context.getBean("helloServiceClient", HelloService.class); Assertions.assertNotNull(helloServiceClient); Assertions.assertInstanceOf(HelloService.class, helloServiceClient); Class<? extends HelloService> clientClass = helloServiceClient.getClass(); Assertions.assertFalse(Modifier.isFinal(clientClass.getModifiers())); Assertions.assertEquals("Hello, dubbo", helloServiceClient.sayHello("dubbo")); } finally { if (context != null) { context.close(); } } } @Test void testLazyProxy3() { AnnotationConfigApplicationContext context = null; try { context = new AnnotationConfigApplicationContext(CommonConfig.class, LazyProxyConfiguration3.class); HelloService helloServiceClient = context.getBean("helloServiceClient", HelloService.class); Assertions.assertNotNull(helloServiceClient); Assertions.assertInstanceOf(HelloService.class, helloServiceClient); Class<? extends HelloService> clientClass = helloServiceClient.getClass(); Assertions.assertTrue(Modifier.isFinal(clientClass.getModifiers())); Assertions.assertEquals("Hello, dubbo", helloServiceClient.sayHello("dubbo")); } finally { if (context != null) { context.close(); } } } private String getStackTrace(Throwable ex) { StringWriter stringWriter = new StringWriter(); ex.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } @Test void testAnnotationBean() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CommonConfig.class, AnnotationBeanConfiguration.class); try { Map<String, HelloService> helloServiceMap = context.getBeansOfType(HelloService.class); Assertions.assertEquals(2, helloServiceMap.size()); Assertions.assertNotNull(helloServiceMap.get("helloService")); Assertions.assertNotNull(helloServiceMap.get("helloServiceImpl")); Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(1, referenceBeanMap.size()); ReferenceBean referenceBean = referenceBeanMap.get("&helloService"); Assertions.assertEquals("demo", referenceBean.getGroup()); Assertions.assertEquals(HelloService.class, referenceBean.getInterfaceClass()); Assertions.assertEquals(HelloService.class.getName(), referenceBean.getServiceInterface()); } finally { context.close(); } } @Test void testGenericServiceAnnotationBean() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( CommonConfig.class, GenericServiceAnnotationBeanConfiguration.class); try { Map<String, HelloService> helloServiceMap = context.getBeansOfType(HelloService.class); Assertions.assertEquals(1, helloServiceMap.size()); Assertions.assertNotNull(helloServiceMap.get("helloServiceImpl")); Map<String, GenericService> genericServiceMap = context.getBeansOfType(GenericService.class); Assertions.assertEquals(3, genericServiceMap.size()); Assertions.assertNotNull(genericServiceMap.get("genericHelloService")); Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(2, referenceBeanMap.size()); ReferenceBean genericHelloServiceReferenceBean = referenceBeanMap.get("&genericHelloService"); Assertions.assertEquals("demo", genericHelloServiceReferenceBean.getGroup()); Assertions.assertEquals(GenericService.class, genericHelloServiceReferenceBean.getInterfaceClass()); Assertions.assertEquals( HelloService.class.getName(), genericHelloServiceReferenceBean.getServiceInterface()); ReferenceBean genericServiceWithoutInterfaceBean = referenceBeanMap.get("&genericServiceWithoutInterface"); Assertions.assertEquals("demo", genericServiceWithoutInterfaceBean.getGroup()); Assertions.assertEquals(GenericService.class, genericServiceWithoutInterfaceBean.getInterfaceClass()); Assertions.assertEquals( "org.apache.dubbo.config.spring.api.LocalMissClass", genericServiceWithoutInterfaceBean.getServiceInterface()); GenericService genericServiceWithoutInterface = context.getBean("genericServiceWithoutInterface", GenericService.class); Assertions.assertNotNull(genericServiceWithoutInterface); Object sayHelloResult = genericServiceWithoutInterface.$invoke( "sayHello", new String[] {"java.lang.String"}, new Object[] {"Dubbo"}); Assertions.assertEquals("Hello Dubbo", sayHelloResult); } finally { context.close(); } } @Test void testReferenceBean() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CommonConfig.class, ReferenceBeanConfiguration.class); try { Map<String, HelloService> helloServiceMap = context.getBeansOfType(HelloService.class); Assertions.assertEquals(2, helloServiceMap.size()); Assertions.assertNotNull(helloServiceMap.get("helloService")); Assertions.assertNotNull(helloServiceMap.get("helloServiceImpl")); Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(2, referenceBeanMap.size()); ReferenceBean referenceBean = referenceBeanMap.get("&helloService"); Assertions.assertEquals(HelloService.class, referenceBean.getInterfaceClass()); Assertions.assertEquals(HelloService.class.getName(), referenceBean.getServiceInterface()); ReferenceBean demoServiceReferenceBean = referenceBeanMap.get("&demoService"); Assertions.assertEquals(DemoService.class, demoServiceReferenceBean.getInterfaceClass()); Assertions.assertEquals(DemoService.class.getName(), demoServiceReferenceBean.getServiceInterface()); } finally { context.close(); } } @Test void testGenericServiceReferenceBean() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( CommonConfig.class, GenericServiceReferenceBeanConfiguration.class); try { Map<String, HelloService> helloServiceMap = context.getBeansOfType(HelloService.class); Assertions.assertEquals(1, helloServiceMap.size()); Assertions.assertNotNull(helloServiceMap.get("helloServiceImpl")); Map<String, GenericService> genericServiceMap = context.getBeansOfType(GenericService.class); Assertions.assertEquals(2, genericServiceMap.size()); Assertions.assertNotNull(genericServiceMap.get("localMissClassGenericServiceImpl")); Assertions.assertNotNull(genericServiceMap.get("genericHelloService")); Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(1, referenceBeanMap.size()); ReferenceBean genericHelloServiceReferenceBean = referenceBeanMap.get("&genericHelloService"); Assertions.assertEquals("demo", genericHelloServiceReferenceBean.getGroup()); Assertions.assertEquals(GenericService.class, genericHelloServiceReferenceBean.getInterfaceClass()); Assertions.assertEquals( HelloService.class.getName(), genericHelloServiceReferenceBean.getServiceInterface()); } finally { context.close(); } } @Test void testRawReferenceBean() { AnnotationConfigApplicationContext context = null; try { context = new AnnotationConfigApplicationContext( CommonConfig.class, ReferenceBeanWithoutGenericTypeConfiguration.class); Assertions.fail("Should not load application"); } catch (Exception e) { String s = e.toString(); Assertions.assertTrue(s.contains("The ReferenceBean is missing necessary generic type"), s); Assertions.assertTrue(s.contains("ReferenceBeanWithoutGenericTypeConfiguration#helloService()"), s); } finally { if (context != null) { context.close(); } } } @Test void testInconsistentBean() { AnnotationConfigApplicationContext context = null; try { context = new AnnotationConfigApplicationContext(CommonConfig.class, InconsistentBeanConfiguration.class); Assertions.fail("Should not load application"); } catch (Exception e) { String s = e.toString(); Assertions.assertTrue( s.contains("@DubboReference annotation is inconsistent with the generic type of the ReferenceBean"), s); Assertions.assertTrue(s.contains("ReferenceBean<org.apache.dubbo.config.spring.api.HelloService>"), s); Assertions.assertTrue(s.contains("InconsistentBeanConfiguration#helloService()"), s); } finally { if (context != null) { context.close(); } } } @Test void testMissingGenericTypeBean() { AnnotationConfigApplicationContext context = null; try { context = new AnnotationConfigApplicationContext( CommonConfig.class, MissingGenericTypeAnnotationBeanConfiguration.class); Assertions.fail("Should not load application"); } catch (Exception e) { String s = e.toString(); Assertions.assertTrue(s.contains("The ReferenceBean is missing necessary generic type"), s); Assertions.assertTrue(s.contains("MissingGenericTypeAnnotationBeanConfiguration#helloService()"), s); } finally { if (context != null) { context.close(); } } } @Test void testMissingInterfaceTypeBean() { AnnotationConfigApplicationContext context = null; try { context = new AnnotationConfigApplicationContext( CommonConfig.class, MissingInterfaceTypeAnnotationBeanConfiguration.class); Assertions.fail("Should not load application"); } catch (Exception e) { String s = e.toString(); Assertions.assertTrue(s.contains("The interface class or name of reference was not found"), s); } finally { if (context != null) { context.close(); } } } @Configuration @EnableDubbo @PropertySource("classpath:/org/apache/dubbo/config/spring/reference/javaconfig/consumer.properties") public static class CommonConfig { @Bean public List<String> testBean(HelloService helloService) { return Arrays.asList(helloService.getClass().getName()); } @Bean @DubboService(group = "${myapp.group}") public HelloService helloServiceImpl() { return new HelloServiceImpl(); } @Bean @DubboService(group = "${myapp.group}", interfaceName = "org.apache.dubbo.config.spring.api.LocalMissClass") public GenericService localMissClassGenericServiceImpl() { return new GenericService() { @Override public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException { if ("sayHello".equals(method)) { return "Hello " + args[0]; } return null; } }; } } @Configuration public static class LazyProxyConfiguration1 { @DubboReference(group = "${myapp.group}") private HelloService helloService; @Bean(name = "helloServiceClient") public HelloService helloService() { return helloService; } } @Configuration public static class LazyProxyConfiguration2 { @DubboReference(group = "${myapp.group}", proxy = "javassist") private HelloService helloService; @Bean(name = "helloServiceClient") public HelloService helloService() { return helloService; } } @Configuration public static class LazyProxyConfiguration3 { @DubboReference(group = "${myapp.group}", proxy = "jdk") private HelloService helloService; @Bean(name = "helloServiceClient") public HelloService helloService() { return helloService; } } @Configuration public static class AnnotationAtFieldConfiguration { @DubboReference(group = "${myapp.group}") private HelloService helloService; } @Configuration public static class AnnotationAtFieldConfiguration2 { @DubboReference(group = "${myapp.group}", timeout = 2000) private HelloService helloService; } @Configuration public static class AnnotationBeanConfiguration { @Bean @DubboReference(group = "${myapp.group}") public ReferenceBean<HelloService> helloService() { return new ReferenceBean(); } } @Configuration public static class GenericServiceAnnotationBeanConfiguration { @Bean @Reference(group = "${myapp.group}", interfaceClass = HelloService.class) public ReferenceBean<GenericService> genericHelloService() { return new ReferenceBean(); } @Bean @DubboReference( group = "${myapp.group}", interfaceName = "org.apache.dubbo.config.spring.api.LocalMissClass", scope = "local") public ReferenceBean<GenericService> genericServiceWithoutInterface() { return new ReferenceBean(); } } @Configuration public static class ReferenceBeanConfiguration { @Bean public ReferenceBean<HelloService> helloService() { return new ReferenceBeanBuilder().setGroup("${myapp.group}").build(); } @Bean public ReferenceBean<DemoService> demoService() { return new ReferenceBean(); } } @Configuration public static class GenericServiceReferenceBeanConfiguration { @Bean public ReferenceBean<GenericService> genericHelloService() { return new ReferenceBeanBuilder() .setGroup("${myapp.group}") .setInterface(HelloService.class) .build(); } } @Configuration public static class ReferenceBeanWithoutGenericTypeConfiguration { // The ReferenceBean is missing necessary generic type @Bean public ReferenceBean helloService() { return new ReferenceBeanBuilder() .setGroup("${myapp.group}") .setInterface(HelloService.class) .build(); } } @Configuration public static class InconsistentBeanConfiguration { // The 'interfaceClass' or 'interfaceName' attribute value of @DubboReference annotation is inconsistent with // the generic type of the ReferenceBean returned by the bean method. @Bean @DubboReference(group = "${myapp.group}", interfaceClass = DemoService.class) public ReferenceBean<HelloService> helloService() { return new ReferenceBean(); } } @Configuration public static class MissingGenericTypeAnnotationBeanConfiguration { // The ReferenceBean is missing necessary generic type @Bean @DubboReference(group = "${myapp.group}", interfaceClass = DemoService.class) public ReferenceBean helloService() { return new ReferenceBean(); } } @Configuration public static class MissingInterfaceTypeAnnotationBeanConfiguration { // The ReferenceBean is missing necessary generic type @Bean @DubboReference(group = "${myapp.group}") public ReferenceBean<GenericService> helloService() { return new ReferenceBean(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/DubboXmlProviderTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/DubboXmlProviderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference.registryNA.provider; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.SysProps; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.rpc.RpcException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DubboXmlProviderTest { @BeforeEach void setUp() { DubboBootstrap.reset(); SysProps.clear(); SysProps.setProperty("dubbo.metrics.enabled", "false"); SysProps.setProperty("dubbo.metrics.protocol", "disabled"); } @AfterEach void tearDown() { DubboBootstrap.reset(); SysProps.clear(); } @Test void testProvider() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "classpath:/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml"); context.start(); Object bean = context.getBean("helloService"); Assertions.assertNotNull(bean); } @Test void testProvider2() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "classpath:/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml"); context.start(); Assertions.assertNotNull(context.getBean("helloService")); ClassPathXmlApplicationContext context2 = new ClassPathXmlApplicationContext( "classpath:/org/apache/dubbo/config/spring/reference/registryNA/consumer/dubbo-consumer.xml"); context2.start(); HelloService helloService = context2.getBean("helloService", HelloService.class); Assertions.assertNotNull(helloService); RpcException exception = Assertions.assertThrows(RpcException.class, () -> helloService.sayHello("dubbo")); Assertions.assertTrue( exception .getMessage() .contains( "Failed to invoke the method sayHello in the service org.apache.dubbo.config.spring.api.HelloService. No provider available for the service org.apache.dubbo.config.spring.api.HelloService")); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/consumer/DubboXmlConsumerTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/consumer/DubboXmlConsumerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference.registryNA.consumer; import org.apache.dubbo.config.spring.api.HelloService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; class DubboXmlConsumerTest { @Test void testConsumer() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "classpath:/org/apache/dubbo/config/spring/reference/registryNA/consumer/dubbo-registryNA-consumer.xml"); context.start(); HelloService helloService = context.getBean("helloService", HelloService.class); IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class, () -> helloService.sayHello("dubbo")); Assertions.assertTrue(exception .getMessage() .contains("No such any registry to reference org.apache.dubbo.config.spring.api.HelloService")); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedReference.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedReference.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.annotation.merged; import org.apache.dubbo.config.annotation.Reference; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Reference public @interface MergedReference { @AliasFor(annotation = Reference.class, attribute = "group") String group() default "dubbo"; @AliasFor(annotation = Reference.class, attribute = "version") String version() default "1.0.0"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedService.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/merged/MergedService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.annotation.merged; import org.apache.dubbo.config.annotation.Service; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Service public @interface MergedService { @AliasFor(annotation = Service.class, attribute = "group") String group() default "dubbo"; @AliasFor(annotation = Service.class, attribute = "version") String version() default "1.0.0"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/provider/AnnotationServiceImpl.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/provider/AnnotationServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.annotation.provider; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.spring.api.Box; import org.apache.dubbo.config.spring.api.DemoService; /** * DemoServiceImpl */ @Service(version = "${provider.version}") public class AnnotationServiceImpl implements DemoService { public String sayName(String name) { return "annotation:" + name; } public Box getBox() { return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/consumer/AnnotationAction.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/annotation/consumer/AnnotationAction.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.annotation.consumer; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.spring.api.DemoService; import org.springframework.stereotype.Controller; @Controller("annotationAction") public class AnnotationAction { @Reference( version = "1.2", methods = {@Method(name = "sayName", timeout = 5000)}) private DemoService demoService; public String doSayName(String name) { return demoService.sayName(name); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional1/XmlReferenceBeanConditionalTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional1/XmlReferenceBeanConditionalTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.boot.conditional1; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; import java.util.Map; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.core.annotation.Order; /** * issue: https://github.com/apache/dubbo-spring-boot-project/issues/779 */ @SpringBootTest( properties = {"dubbo.registry.address=N/A"}, classes = {XmlReferenceBeanConditionalTest.class}) @Configuration // @ComponentScan class XmlReferenceBeanConditionalTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Autowired private HelloService helloService; @Autowired private ApplicationContext applicationContext; @Test void testConsumer() { Map<String, HelloService> helloServiceMap = applicationContext.getBeansOfType(HelloService.class); Assertions.assertEquals(1, helloServiceMap.size()); Assertions.assertNotNull(helloServiceMap.get("helloService")); Assertions.assertNull(helloServiceMap.get("myHelloService")); } @Order(Integer.MAX_VALUE - 2) @Configuration @ImportResource("classpath:/org/apache/dubbo/config/spring/boot/conditional1/consumer/dubbo-consumer.xml") public static class ConsumerConfiguration {} @Order(Integer.MAX_VALUE - 1) @Configuration public static class ConsumerConfiguration2 { // TEST Conditional, this bean should be ignored @Bean @ConditionalOnMissingBean public HelloService myHelloService() { return new HelloService() { @Override public String sayHello(String name) { return "HI, " + name; } }; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootConfigPropsTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootConfigPropsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.boot.configprops; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.context.ModuleConfigManager; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import java.util.Collection; import java.util.List; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; @SpringBootTest( properties = { "dubbo.application.NAME = dubbo-demo-application", "dubbo.module.name = dubbo-demo-module", "dubbo.registry.address = zookeeper://192.168.99.100:32770", "dubbo.protocol.name=dubbo", "dubbo.protocol.port=20880", "dubbo.metrics.protocol=prometheus", "dubbo.metrics.enable-jvm=true", "dubbo.metrics.prometheus.exporter.enabled=true", "dubbo.metrics.prometheus.exporter.enable-http-service-discovery=true", "dubbo.metrics.prometheus.exporter.http-service-discovery-url=localhost:8080", "dubbo.metrics.aggregation.enabled=true", "dubbo.metrics.aggregation.bucket-num=5", "dubbo.metrics.aggregation.time-window-seconds=120", "dubbo.metrics.histogram.enabled=true", "dubbo.monitor.address=zookeeper://127.0.0.1:32770", "dubbo.Config-center.address=${zookeeper.connection.address.1}", "dubbo.config-Center.group=group1", "dubbo.metadata-report.address=${zookeeper.connection.address.2}", "dubbo.METADATA-REPORT.username=User", "dubbo.provider.host=127.0.0.1", "dubbo.consumer.client=netty" }, classes = {SpringBootConfigPropsTest.class}) @Configuration @ComponentScan @EnableDubbo class SpringBootConfigPropsTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Autowired private ConfigManager configManager; @Autowired private ModuleModel moduleModel; @Test void testConfigProps() { ApplicationConfig applicationConfig = configManager.getApplicationOrElseThrow(); Assertions.assertEquals("dubbo-demo-application", applicationConfig.getName()); MonitorConfig monitorConfig = configManager.getMonitor().get(); Assertions.assertEquals("zookeeper://127.0.0.1:32770", monitorConfig.getAddress()); MetricsConfig metricsConfig = configManager.getMetrics().get(); Assertions.assertEquals(PROTOCOL_PROMETHEUS, metricsConfig.getProtocol()); Assertions.assertTrue(metricsConfig.getPrometheus().getExporter().getEnabled()); Assertions.assertTrue(metricsConfig.getPrometheus().getExporter().getEnableHttpServiceDiscovery()); Assertions.assertEquals( "localhost:8080", metricsConfig.getPrometheus().getExporter().getHttpServiceDiscoveryUrl()); Assertions.assertEquals(5, metricsConfig.getAggregation().getBucketNum()); Assertions.assertEquals(120, metricsConfig.getAggregation().getTimeWindowSeconds()); Assertions.assertTrue(metricsConfig.getAggregation().getEnabled()); Assertions.assertTrue(metricsConfig.getHistogram().getEnabled()); List<ProtocolConfig> defaultProtocols = configManager.getDefaultProtocols(); Assertions.assertEquals(1, defaultProtocols.size()); ProtocolConfig protocolConfig = defaultProtocols.get(0); Assertions.assertEquals("dubbo", protocolConfig.getName()); Assertions.assertEquals(20880, protocolConfig.getPort()); List<RegistryConfig> defaultRegistries = configManager.getDefaultRegistries(); Assertions.assertEquals(1, defaultRegistries.size()); RegistryConfig registryConfig = defaultRegistries.get(0); Assertions.assertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress()); Collection<ConfigCenterConfig> configCenters = configManager.getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); ConfigCenterConfig centerConfig = configCenters.iterator().next(); Assertions.assertEquals(ZookeeperRegistryCenterConfig.getConnectionAddress1(), centerConfig.getAddress()); Assertions.assertEquals("group1", centerConfig.getGroup()); Collection<MetadataReportConfig> metadataConfigs = configManager.getMetadataConfigs(); Assertions.assertEquals(1, metadataConfigs.size()); MetadataReportConfig reportConfig = metadataConfigs.iterator().next(); Assertions.assertEquals(ZookeeperRegistryCenterConfig.getConnectionAddress2(), reportConfig.getAddress()); Assertions.assertEquals("User", reportConfig.getUsername()); // module configs ModuleConfigManager moduleConfigManager = moduleModel.getConfigManager(); ModuleConfig moduleConfig = moduleConfigManager.getModule().get(); Assertions.assertEquals("dubbo-demo-module", moduleConfig.getName()); ProviderConfig providerConfig = moduleConfigManager.getDefaultProvider().get(); Assertions.assertEquals("127.0.0.1", providerConfig.getHost()); ConsumerConfig consumerConfig = moduleConfigManager.getDefaultConsumer().get(); Assertions.assertEquals("netty", consumerConfig.getClient()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootMultipleConfigPropsTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/configprops/SpringBootMultipleConfigPropsTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.boot.configprops; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.context.ModuleConfigManager; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import java.util.Collection; import java.util.List; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; @SpringBootTest( properties = { "dubbo.applications.application1.name = dubbo-demo-application", "dubbo.modules.demo-module.name = dubbo-demo-module", "dubbo.registries.my-registry.address = zookeeper://192.168.99.100:32770", "dubbo.protocols.dubbo.port=20880", "dubbo.metricses.my-metrics.protocol=prometheus", "dubbo.metricses.my-metrics.prometheus.pushgateway.enabled=true", "dubbo.metricses.my-metrics.prometheus.pushgateway.base-url=localhost:9091", "dubbo.metricses.my-metrics.prometheus.pushgateway.username=username", "dubbo.metricses.my-metrics.prometheus.pushgateway.password=password", "dubbo.metricses.my-metrics.prometheus.pushgateway.job=job", "dubbo.metricses.my-metrics.prometheus.pushgateway.push-interval=30", "dubbo.metricses.my-metrics.aggregation.enabled=true", "dubbo.metricses.my-metrics.aggregation.bucket-num=5", "dubbo.metricses.my-metrics.aggregation.time-window-seconds=120", "dubbo.metricses.my-metrics.histogram.enabled=true", "dubbo.monitors.my-monitor.address=zookeeper://127.0.0.1:32770", "dubbo.config-centers.my-configcenter.address=${zookeeper.connection.address.1}", "dubbo.config-centers.my-configcenter.group=group1", "dubbo.metadata-reports.my-metadata.address=${zookeeper.connection.address.2}", "dubbo.metadata-reports.my-metadata.username=User", "dubbo.providers.my-provider.host=127.0.0.1", "dubbo.consumers.my-consumer.client=netty" }, classes = {SpringBootMultipleConfigPropsTest.class}) @Configuration @ComponentScan @EnableDubbo class SpringBootMultipleConfigPropsTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Autowired private ConfigManager configManager; @Autowired private ModuleModel moduleModel; @Test void testConfigProps() { ApplicationConfig applicationConfig = configManager.getApplicationOrElseThrow(); Assertions.assertEquals("dubbo-demo-application", applicationConfig.getName()); MonitorConfig monitorConfig = configManager.getMonitor().get(); Assertions.assertEquals("zookeeper://127.0.0.1:32770", monitorConfig.getAddress()); MetricsConfig metricsConfig = configManager.getMetrics().get(); Assertions.assertEquals(PROTOCOL_PROMETHEUS, metricsConfig.getProtocol()); Assertions.assertTrue(metricsConfig.getPrometheus().getPushgateway().getEnabled()); Assertions.assertEquals( "localhost:9091", metricsConfig.getPrometheus().getPushgateway().getBaseUrl()); Assertions.assertEquals( "username", metricsConfig.getPrometheus().getPushgateway().getUsername()); Assertions.assertEquals( "password", metricsConfig.getPrometheus().getPushgateway().getPassword()); Assertions.assertEquals( "job", metricsConfig.getPrometheus().getPushgateway().getJob()); Assertions.assertEquals( 30, metricsConfig.getPrometheus().getPushgateway().getPushInterval()); Assertions.assertEquals(5, metricsConfig.getAggregation().getBucketNum()); Assertions.assertEquals(120, metricsConfig.getAggregation().getTimeWindowSeconds()); Assertions.assertTrue(metricsConfig.getAggregation().getEnabled()); Assertions.assertTrue(metricsConfig.getHistogram().getEnabled()); List<ProtocolConfig> defaultProtocols = configManager.getDefaultProtocols(); Assertions.assertEquals(1, defaultProtocols.size()); ProtocolConfig protocolConfig = defaultProtocols.get(0); Assertions.assertEquals("dubbo", protocolConfig.getName()); Assertions.assertEquals(20880, protocolConfig.getPort()); List<RegistryConfig> defaultRegistries = configManager.getDefaultRegistries(); Assertions.assertEquals(1, defaultRegistries.size()); RegistryConfig registryConfig = defaultRegistries.get(0); Assertions.assertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress()); Collection<ConfigCenterConfig> configCenters = configManager.getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); ConfigCenterConfig centerConfig = configCenters.iterator().next(); Assertions.assertEquals(ZookeeperRegistryCenterConfig.getConnectionAddress1(), centerConfig.getAddress()); Assertions.assertEquals("group1", centerConfig.getGroup()); Collection<MetadataReportConfig> metadataConfigs = configManager.getMetadataConfigs(); Assertions.assertEquals(1, metadataConfigs.size()); MetadataReportConfig reportConfig = metadataConfigs.iterator().next(); Assertions.assertEquals(ZookeeperRegistryCenterConfig.getConnectionAddress2(), reportConfig.getAddress()); Assertions.assertEquals("User", reportConfig.getUsername()); // module configs ModuleConfigManager moduleConfigManager = moduleModel.getConfigManager(); ModuleConfig moduleConfig = moduleConfigManager.getModule().get(); Assertions.assertEquals("dubbo-demo-module", moduleConfig.getName()); ProviderConfig providerConfig = moduleConfigManager.getDefaultProvider().get(); Assertions.assertEquals("127.0.0.1", providerConfig.getHost()); ConsumerConfig consumerConfig = moduleConfigManager.getDefaultConsumer().get(); Assertions.assertEquals("netty", consumerConfig.getClient()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml/SpringBootImportDubboXmlTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml/SpringBootImportDubboXmlTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.boot.importxml; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.HelloService; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @SpringBootTest( properties = {"dubbo.registry.protocol=zookeeper", "dubbo.registry.address=localhost:2181"}, classes = {SpringBootImportDubboXmlTest.class}) @Configuration @ComponentScan @ImportResource("classpath:/org/apache/dubbo/config/spring/boot/importxml/consumer/dubbo-consumer.xml") class SpringBootImportDubboXmlTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Autowired private HelloService helloService; @Test void testConsumer() { try { helloService.sayHello("dubbo"); Assertions.fail("Should not be called successfully"); } catch (Exception e) { String s = e.toString(); Assertions.assertTrue(s.contains("No provider available"), s); Assertions.assertTrue(s.contains("service org.apache.dubbo.config.spring.api.HelloService"), s); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional2/JavaConfigAnnotationReferenceBeanConditionalTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional2/JavaConfigAnnotationReferenceBeanConditionalTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.boot.conditional2; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.context.annotation.provider.HelloServiceImpl; import java.util.Map; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; /** * issue: https://github.com/apache/dubbo-spring-boot-project/issues/779 */ @SpringBootTest( properties = {"dubbo.application.name=consumer-app", "dubbo.registry.address=N/A", "myapp.group=demo"}, classes = {JavaConfigAnnotationReferenceBeanConditionalTest.class}) @Configuration // @ComponentScan @EnableDubbo class JavaConfigAnnotationReferenceBeanConditionalTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Autowired private HelloService helloService; @Autowired private ApplicationContext applicationContext; @Test void testConsumer() { Map<String, HelloService> helloServiceMap = applicationContext.getBeansOfType(HelloService.class); Assertions.assertEquals(1, helloServiceMap.size()); Assertions.assertNotNull(helloServiceMap.get("helloService")); Assertions.assertNull(helloServiceMap.get("myHelloService")); } @Order(Integer.MAX_VALUE - 2) @Configuration public static class AnnotationBeanConfiguration { @Bean @DubboReference(group = "${myapp.group}", init = false) public ReferenceBean<HelloService> helloService() { return new ReferenceBean(); } } @Order(Integer.MAX_VALUE - 1) @Configuration public static class ConditionalBeanConfiguration { // TEST Conditional, this bean should be ignored @Bean @ConditionalOnMissingBean public HelloService myHelloService() { return new HelloServiceImpl(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/HelloServiceImpl.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/HelloServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.boot.importxml2; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.spring.api.HelloService; @DubboService(group = "${myapp.group:foo2}") public class HelloServiceImpl implements HelloService { @Override public String sayHello(String name) { return "Hello, " + name; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/SpringBootImportAndScanTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/importxml2/SpringBootImportAndScanTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.boot.importxml2; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; import org.apache.dubbo.config.spring.reference.ReferenceBeanManager; import java.util.Map; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @SpringBootTest( properties = { // "dubbo.scan.base-packages=org.apache.dubbo.config.spring.boot.importxml2", "dubbo.registry.address=N/A", "myapp.dubbo.port=20881", "myapp.name=dubbo-provider", "myapp.group=test" }, classes = SpringBootImportAndScanTest.class) @Configuration @ComponentScan @DubboComponentScan @ImportResource("classpath:/org/apache/dubbo/config/spring/boot/importxml2/dubbo-provider.xml") class SpringBootImportAndScanTest implements ApplicationContextAware { private ApplicationContext applicationContext; @BeforeAll public static void setUp() { DubboBootstrap.reset(); } @AfterAll public static void tearDown() { DubboBootstrap.reset(); } @Autowired private HelloService helloService; @Test void testProvider() { String result = helloService.sayHello("dubbo"); Assertions.assertEquals("Hello, dubbo", result); Map<String, ReferenceBean> referenceBeanMap = applicationContext.getBeansOfType(ReferenceBean.class); Assertions.assertEquals(1, referenceBeanMap.size()); Assertions.assertNotNull(referenceBeanMap.get("&helloService")); ReferenceBeanManager referenceBeanManager = applicationContext.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); Assertions.assertNotNull(referenceBeanManager.getById("helloService")); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Configuration public static class ConsumerConfiguration { // Match and reuse 'helloService' reference bean definition in dubbo-provider.xml @DubboReference(group = "${myapp.group}") private HelloService helloService; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional3/JavaConfigRawReferenceBeanConditionalTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional3/JavaConfigRawReferenceBeanConditionalTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.boot.conditional3; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.context.annotation.provider.HelloServiceImpl; import org.apache.dubbo.config.spring.reference.ReferenceBeanBuilder; import java.util.Map; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; /** * issue: https://github.com/apache/dubbo-spring-boot-project/issues/779 */ @SpringBootTest( properties = {"dubbo.application.name=consumer-app", "dubbo.registry.address=N/A", "myapp.group=demo"}, classes = {JavaConfigRawReferenceBeanConditionalTest.class}) @Configuration // @ComponentScan @EnableDubbo class JavaConfigRawReferenceBeanConditionalTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Autowired private HelloService helloService; @Autowired private ApplicationContext applicationContext; @Test void testConsumer() { Map<String, HelloService> helloServiceMap = applicationContext.getBeansOfType(HelloService.class); Assertions.assertEquals(1, helloServiceMap.size()); Assertions.assertNotNull(helloServiceMap.get("helloService")); Assertions.assertNull(helloServiceMap.get("myHelloService")); } @Order(Integer.MAX_VALUE - 2) @Configuration public static class RawReferenceBeanConfiguration { @Bean public ReferenceBean<HelloService> helloService() { return new ReferenceBeanBuilder() .setGroup("${myapp.group}") .setInit(false) .build(); } } @Order(Integer.MAX_VALUE - 1) @Configuration public static class ConditionalBeanConfiguration { // TEST Conditional, this bean should be ignored @Bean @ConditionalOnMissingBean public HelloService myHelloService() { return new HelloServiceImpl(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional4/JavaConfigReferenceBeanConditionalTest4.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/boot/conditional4/JavaConfigReferenceBeanConditionalTest4.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.boot.conditional4; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.context.annotation.provider.HelloServiceImpl; import java.util.Map; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; /** * issue: https://github.com/apache/dubbo-spring-boot-project/issues/779 */ @SpringBootTest( properties = {"dubbo.application.name=consumer-app", "dubbo.registry.address=N/A", "myapp.group=demo"}, classes = {JavaConfigReferenceBeanConditionalTest4.class}) @Configuration // @ComponentScan @EnableDubbo public class JavaConfigReferenceBeanConditionalTest4 { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Autowired private HelloService helloService; @Autowired private ApplicationContext applicationContext; @Test public void testConsumer() { Map<String, HelloService> helloServiceMap = applicationContext.getBeansOfType(HelloService.class); Assertions.assertEquals(1, helloServiceMap.size()); Assertions.assertNull(helloServiceMap.get("helloService")); HelloService helloService = helloServiceMap.get("helloServiceImpl"); Assertions.assertNotNull(helloService); Assertions.assertTrue( helloService instanceof HelloServiceImpl, "Not expected bean type: " + helloService.getClass()); } @Order(Integer.MAX_VALUE - 2) @Configuration public static class ServiceBeanConfiguration { @Bean public HelloService helloServiceImpl() { return new HelloServiceImpl(); } } // make sure that the one using condition runs after. @Order(Integer.MAX_VALUE - 1) @Configuration public static class AnnotationBeanConfiguration { // TEST Conditional, this bean should be ignored @Bean @ConditionalOnMissingBean(HelloService.class) @DubboReference(group = "${myapp.group}", init = false) public ReferenceBean<HelloService> helloService() { return new ReferenceBean(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/DataSourceStatusCheckerTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/DataSourceStatusCheckerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.status; import org.apache.dubbo.common.status.Status; import org.apache.dubbo.config.spring.ServiceBean; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Answers; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.context.ApplicationContext; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.MockitoAnnotations.initMocks; class DataSourceStatusCheckerTest { private DataSourceStatusChecker dataSourceStatusChecker; @Mock private ApplicationContext applicationContext; @BeforeEach public void setUp() throws Exception { initMocks(this); this.dataSourceStatusChecker = new DataSourceStatusChecker(applicationContext); new ServiceBean<Object>(applicationContext).setApplicationContext(applicationContext); } @AfterEach public void tearDown() throws Exception { Mockito.reset(applicationContext); } @Test void testWithoutApplicationContext() { Status status = dataSourceStatusChecker.check(); assertThat(status.getLevel(), is(Status.Level.UNKNOWN)); } @Test void testWithoutDatasource() { Map<String, DataSource> map = new HashMap<String, DataSource>(); given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean())) .willReturn(map); Status status = dataSourceStatusChecker.check(); assertThat(status.getLevel(), is(Status.Level.UNKNOWN)); } @Test void testWithDatasourceHasNextResult() throws SQLException { Map<String, DataSource> map = new HashMap<String, DataSource>(); DataSource dataSource = mock(DataSource.class); Connection connection = mock(Connection.class, Answers.RETURNS_DEEP_STUBS); given(dataSource.getConnection()).willReturn(connection); given(connection.getMetaData().getTypeInfo().next()).willReturn(true); map.put("mockDatabase", dataSource); given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean())) .willReturn(map); Status status = dataSourceStatusChecker.check(); assertThat(status.getLevel(), is(Status.Level.OK)); } @Test void testWithDatasourceNotHasNextResult() throws SQLException { Map<String, DataSource> map = new HashMap<String, DataSource>(); DataSource dataSource = mock(DataSource.class); Connection connection = mock(Connection.class, Answers.RETURNS_DEEP_STUBS); given(dataSource.getConnection()).willReturn(connection); given(connection.getMetaData().getTypeInfo().next()).willReturn(false); map.put("mockDatabase", dataSource); given(applicationContext.getBeansOfType(eq(DataSource.class), anyBoolean(), anyBoolean())) .willReturn(map); Status status = dataSourceStatusChecker.check(); assertThat(status.getLevel(), is(Status.Level.ERROR)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/SpringStatusCheckerTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/status/SpringStatusCheckerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.status; import org.apache.dubbo.common.status.Status; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.Lifecycle; import org.springframework.web.context.support.GenericWebApplicationContext; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; class SpringStatusCheckerTest { // @Mock // private ApplicationLifeCycle applicationContext; @BeforeEach public void setUp() throws Exception { // initMocks(this); } @AfterEach public void tearDown() throws Exception { // Mockito.reset(applicationContext); } @Test void testWithoutApplicationContext() { SpringStatusChecker springStatusChecker = new SpringStatusChecker((ApplicationContext) null); Status status = springStatusChecker.check(); assertThat(status.getLevel(), is(Status.Level.UNKNOWN)); } @Test void testWithLifeCycleRunning() { ApplicationLifeCycle applicationLifeCycle = mock(ApplicationLifeCycle.class); given(applicationLifeCycle.getConfigLocations()).willReturn(new String[] {"test1", "test2"}); given(applicationLifeCycle.isRunning()).willReturn(true); SpringStatusChecker springStatusChecker = new SpringStatusChecker(applicationLifeCycle); Status status = springStatusChecker.check(); assertThat(status.getLevel(), is(Status.Level.OK)); assertThat(status.getMessage(), is("test1,test2")); } @Test void testWithoutLifeCycleRunning() { ApplicationLifeCycle applicationLifeCycle = mock(ApplicationLifeCycle.class); given(applicationLifeCycle.isRunning()).willReturn(false); SpringStatusChecker springStatusChecker = new SpringStatusChecker(applicationLifeCycle); Status status = springStatusChecker.check(); assertThat(status.getLevel(), is(Status.Level.ERROR)); } interface ApplicationLifeCycle extends Lifecycle, ApplicationContext { String[] getConfigLocations(); } // TODO improve GenericWebApplicationContext test scenario @Test void testGenericWebApplicationContext() { GenericWebApplicationContext context = mock(GenericWebApplicationContext.class); given(context.isRunning()).willReturn(true); SpringStatusChecker checker = new SpringStatusChecker(context); Status status = checker.check(); Assertions.assertEquals(Status.Level.OK, status.getLevel()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockServiceDiscovery.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockServiceDiscovery.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.client.AbstractServiceDiscovery; import org.apache.dubbo.registry.client.ServiceInstance; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class MockServiceDiscovery extends AbstractServiceDiscovery { private URL registryURL; public MockServiceDiscovery(ApplicationModel applicationModel, URL registryURL) { super(applicationModel, registryURL); } public MockServiceDiscovery(String serviceName, URL registryURL) { super(serviceName, registryURL); } @Override public void doDestroy() throws Exception {} @Override public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {} @Override public void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) throws RuntimeException {} @Override public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException {} @Override public Set<String> getServices() { return new HashSet<>(); } @Override public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException { return Collections.emptyList(); } @Override public URL getUrl() { return registryURL; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockRegistry.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockRegistry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.NotifyListener; import org.apache.dubbo.registry.Registry; import java.util.ArrayList; import java.util.List; public class MockRegistry implements Registry { private URL url; private List<URL> registered = new ArrayList<URL>(); private List<URL> subscribered = new ArrayList<URL>(); public MockRegistry(URL url) { if (url == null) { throw new NullPointerException(); } this.url = url; } public List<URL> getRegistered() { return registered; } public List<URL> getSubscribered() { return subscribered; } public URL getUrl() { return url; } @Override public boolean isAvailable() { return true; } @Override public void destroy() {} @Override public void register(URL url) { registered.add(url); } @Override public void unregister(URL url) { registered.remove(url); } @Override public void subscribe(URL url, NotifyListener listener) { subscribered.add(url); } @Override public void unsubscribe(URL url, NotifyListener listener) { subscribered.remove(url); } @Override public List<URL> lookup(URL url) { return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockRegistryFactory.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockRegistryFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.registry; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class MockRegistryFactory implements RegistryFactory { private static final Map<URL, Registry> REGISTRIES = new HashMap<URL, Registry>(); public static Collection<Registry> getCachedRegistry() { return REGISTRIES.values(); } public static void cleanCachedRegistry() { REGISTRIES.clear(); } @Override public Registry getRegistry(URL url) { MockRegistry registry = new MockRegistry(url); REGISTRIES.put(url, registry); return registry; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/nacos/NacosServiceNameTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/nacos/NacosServiceNameTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.registry.nacos.nacos; import org.apache.dubbo.registry.nacos.NacosServiceName; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; import static org.apache.dubbo.registry.nacos.NacosServiceName.WILDCARD; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * {@link NacosServiceName} Test * * @since 2.7.3 */ class NacosServiceNameTest { private static final String category = DEFAULT_CATEGORY; private static final String serviceInterface = "org.apache.dubbo.registry.nacos.NacosServiceName"; private static final String version = "1.0.0"; private static final String group = "default"; private final NacosServiceName name = new NacosServiceName(); @BeforeEach public void init() { name.setCategory(category); name.setServiceInterface(serviceInterface); name.setVersion(version); name.setGroup(group); } @Test void testGetter() { assertEquals(category, name.getCategory()); assertEquals(serviceInterface, name.getServiceInterface()); assertEquals(version, name.getVersion()); assertEquals(group, name.getGroup()); assertEquals("providers:org.apache.dubbo.registry.nacos.NacosServiceName:1.0.0:default", name.getValue()); } @Test void testToString() { assertEquals("providers:org.apache.dubbo.registry.nacos.NacosServiceName:1.0.0:default", name.toString()); } @Test void testIsConcrete() { assertTrue(name.isConcrete()); name.setGroup(WILDCARD); assertFalse(name.isConcrete()); init(); name.setVersion(WILDCARD); assertFalse(name.isConcrete()); init(); name.setGroup(null); name.setVersion(null); assertTrue(name.isConcrete()); } @Test void testIsCompatible() { NacosServiceName concrete = new NacosServiceName(); assertFalse(name.isCompatible(concrete)); // set category concrete.setCategory(category); assertFalse(name.isCompatible(concrete)); concrete.setServiceInterface(serviceInterface); assertFalse(name.isCompatible(concrete)); concrete.setVersion(version); assertFalse(name.isCompatible(concrete)); concrete.setGroup(group); assertTrue(name.isCompatible(concrete)); // wildcard cases name.setGroup(WILDCARD); assertTrue(name.isCompatible(concrete)); init(); name.setVersion(WILDCARD); assertTrue(name.isCompatible(concrete)); // range cases init(); name.setGroup(group + ",2.0.0"); assertTrue(name.isCompatible(concrete)); init(); name.setVersion(version + ",2.0.0"); assertTrue(name.isCompatible(concrete)); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DefaultService.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DefaultService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.registry.nacos.demo.service; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.rpc.RpcContext; import org.springframework.beans.factory.annotation.Value; /** * Default {@link DemoService} * * @since 2.6.5 */ @Service(version = "${demo.service.version}") public class DefaultService implements DemoService { @Value("${demo.service.name}") private String serviceName; public String sayName(String name) { RpcContext rpcContext = RpcContext.getServiceContext(); return String.format( "Service [name :%s , protocol: %s , port : %d] %s(\"%s\") : Hello,%s", serviceName, rpcContext.getUrl().getProtocol(), rpcContext.getLocalPort(), rpcContext.getMethodName(), name, name); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DemoService.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DemoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.registry.nacos.demo.service; /** * DemoService * * @since 2.6.5 */ public interface DemoService { String sayName(String name); }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderXmlBootstrap.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderXmlBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.registry.nacos.demo.provider; import java.io.IOException; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * {@link org.apache.dubbo.config.spring.registry.nacos.demo.service.DemoService} provider demo XML bootstrap */ public class DemoServiceProviderXmlBootstrap { public static void main(String[] args) throws IOException { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(); context.setConfigLocation("/META-INF/spring/dubbo-nacos-provider-context.xml"); context.refresh(); System.in.read(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderBootstrap.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.registry.nacos.demo.provider; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import java.io.IOException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.PropertySource; /** * {@link org.apache.dubbo.config.spring.registry.nacos.demo.service.DemoService} provider demo */ @EnableDubbo(scanBasePackages = "org.apache.dubbo.demo.service") @PropertySource(value = "classpath:/nacos-provider-config.properties") public class DemoServiceProviderBootstrap { public static void main(String[] args) throws IOException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(DemoServiceProviderBootstrap.class); context.refresh(); System.in.read(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerXmlBootstrap.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerXmlBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.registry.nacos.demo.consumer; import org.apache.dubbo.config.spring.registry.nacos.demo.service.DemoService; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * {@link DemoService} consumer demo XML bootstrap */ public class DemoServiceConsumerXmlBootstrap { private static final Logger logger = LoggerFactory.getLogger(DemoServiceConsumerXmlBootstrap.class); public static void main(String[] args) throws IOException { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(); context.setConfigLocation("/META-INF/spring/dubbo-nacos-consumer-context.xml"); context.refresh(); for (int i = 1; i <= 5; i++) { DemoService demoService = context.getBean("demoService" + i, DemoService.class); for (int j = 0; j < 10; j++) { logger.info(demoService.sayName("小马哥(mercyblitz)")); } } System.in.read(); context.close(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerBootstrap.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.registry.nacos.demo.consumer; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.apache.dubbo.config.spring.registry.nacos.demo.service.DemoService; import javax.annotation.PostConstruct; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.PropertySource; /** * {@link DemoService} consumer demo */ @EnableDubbo @PropertySource(value = "classpath:/nacos-consumer-config.properties") public class DemoServiceConsumerBootstrap { private static final Logger logger = LoggerFactory.getLogger(DemoServiceConsumerBootstrap.class); @Reference(version = "${demo.service.version}") private DemoService demoService; @PostConstruct public void init() throws InterruptedException { for (int j = 0; j < 10; j++) { logger.info(demoService.sayName("小马哥(mercyblitz)")); } Thread.sleep(TimeUnit.SECONDS.toMillis(5)); } public static void main(String[] args) throws IOException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(DemoServiceConsumerBootstrap.class); context.refresh(); System.in.read(); context.close(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/MyGenericService.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/MyGenericService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.schema; import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericService; public class MyGenericService implements GenericService { public Object $invoke(String methodName, String[] parameterTypes, Object[] args) throws GenericException { if ("sayHello".equals(methodName)) { return "Welcome " + args[0]; } return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.schema; import org.apache.dubbo.config.ServiceConfigBase; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.context.ModuleConfigManager; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.api.DemoService; import org.apache.dubbo.rpc.service.GenericService; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.ImportResource; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = GenericServiceTest.class) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) @ImportResource(locations = "classpath:/META-INF/spring/dubbo-generic-consumer.xml") class GenericServiceTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Autowired @Qualifier("demoServiceRef") private GenericService demoServiceRef; @Autowired @Qualifier("demoService") private ServiceBean serviceBean; @Test void testGeneric() { assertNotNull(demoServiceRef); assertNotNull(serviceBean); ModuleConfigManager configManager = DubboBootstrap.getInstance() .getApplicationModel() .getDefaultModule() .getConfigManager(); ServiceConfigBase<Object> serviceConfig = configManager.getService("demoService"); Assertions.assertEquals(DemoService.class.getName(), serviceConfig.getInterface()); Assertions.assertEquals(true, serviceConfig.isExported()); Object result = demoServiceRef.$invoke("sayHello", new String[] {"java.lang.String"}, new Object[] {"dubbo"}); Assertions.assertEquals("Welcome dubbo", result); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceWithoutInterfaceTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/GenericServiceWithoutInterfaceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.schema; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.config.ReferenceConfigBase; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.rpc.service.GenericService; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.ImportResource; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = GenericServiceWithoutInterfaceTest.class) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) @ImportResource(locations = "classpath:/META-INF/spring/dubbo-generic-consumer-without-interface.xml") class GenericServiceWithoutInterfaceTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Autowired @Qualifier("genericServiceWithoutInterfaceRef") private GenericService genericServiceWithoutInterfaceRef; @Test void testGenericWithoutInterface() { // Test generic service without interface class locally Object result = genericServiceWithoutInterfaceRef.$invoke( "sayHello", new String[] {"java.lang.String"}, new Object[] {"generic"}); Assertions.assertEquals("Welcome generic", result); ReferenceConfigBase<Object> reference = DubboBootstrap.getInstance() .getApplicationModel() .getDefaultModule() .getConfigManager() .getReference("genericServiceWithoutInterfaceRef"); Assertions.assertNull(reference.getServiceInterfaceClass()); Assertions.assertEquals("org.apache.dubbo.config.spring.api.LocalMissClass", reference.getInterface()); Assertions.assertThrows(ClassNotFoundException.class, () -> ClassUtils.forName(reference.getInterface())); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandlerTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/DubboNamespaceHandlerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.schema; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetricsConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfigBase; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.context.ModuleConfigManager; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.SysProps; import org.apache.dubbo.config.spring.api.DemoService; import org.apache.dubbo.config.spring.impl.DemoServiceImpl; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collection; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.ClassPathXmlApplicationContext; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; class DubboNamespaceHandlerTest { private static String resourcePath = "org.apache.dubbo.config.spring".replace('.', '/'); @BeforeEach public void setUp() { DubboBootstrap.reset(); SysProps.clear(); SysProps.setProperty("dubbo.metrics.enabled", "false"); SysProps.setProperty("dubbo.metrics.protocol", "disabled"); } @AfterEach public void tearDown() { DubboBootstrap.reset(); SysProps.clear(); } @Configuration @PropertySource("classpath:/META-INF/demo-provider.properties") @ImportResource(locations = "classpath:/org/apache/dubbo/config/spring/demo-provider.xml") static class XmlConfiguration {} @Test void testProviderXmlOnConfigurationClass() { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.register(XmlConfiguration.class); applicationContext.refresh(); testProviderXml(applicationContext); } @Test void testProviderXml() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( resourcePath + "/demo-provider.xml", resourcePath + "/demo-provider-properties.xml"); ctx.start(); testProviderXml(ctx); } private void testProviderXml(ApplicationContext context) { String appName = "demo-provider"; String configId = ApplicationConfig.class.getName() + "#" + appName + "#0"; Map<String, ApplicationConfig> applicationConfigMap = context.getBeansOfType(ApplicationConfig.class); ApplicationConfig providerAppConfig = context.getBean(configId, ApplicationConfig.class); assertNotNull(providerAppConfig); assertEquals(appName, providerAppConfig.getName()); // assertEquals(configId, providerAppConfig.getId()); ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.class); assertThat(protocolConfig, not(nullValue())); assertThat(protocolConfig.getName(), is("dubbo")); assertThat(protocolConfig.getPort(), is(20813)); ApplicationConfig applicationConfig = context.getBean(ApplicationConfig.class); assertThat(applicationConfig, not(nullValue())); assertThat(applicationConfig.getName(), is("demo-provider")); RegistryConfig registryConfig = context.getBean(RegistryConfig.class); assertThat(registryConfig, not(nullValue())); assertThat(registryConfig.getAddress(), is("N/A")); DemoService service = context.getBean(DemoService.class); assertThat(service, not(nullValue())); } @Test void testMultiProtocol() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/multi-protocol.xml"); ctx.start(); Map<String, ProtocolConfig> protocolConfigMap = ctx.getBeansOfType(ProtocolConfig.class); assertThat(protocolConfigMap.size(), is(2)); ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); Collection<ProtocolConfig> protocolConfigs = configManager.getProtocols(); assertThat(protocolConfigs.size(), is(2)); ProtocolConfig rmiProtocolConfig = configManager.getProtocol("rmi").get(); assertThat(rmiProtocolConfig.getPort(), is(10991)); ProtocolConfig dubboProtocolConfig = configManager.getProtocol("dubbo").get(); assertThat(dubboProtocolConfig.getPort(), is(20881)); } @Test void testDefaultProtocol() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/override-protocol.xml"); ctx.start(); ProtocolConfig protocolConfig = ctx.getBean(ProtocolConfig.class); protocolConfig.refresh(); assertThat(protocolConfig.getName(), is("dubbo")); } @Test void testCustomParameter() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/customize-parameter.xml"); ctx.start(); ProtocolConfig protocolConfig = ctx.getBean(ProtocolConfig.class); assertThat(protocolConfig.getParameters().size(), is(1)); assertThat(protocolConfig.getParameters().get("protocol-paramA"), is("protocol-paramA")); ServiceBean serviceBean = ctx.getBean(ServiceBean.class); assertThat(serviceBean.getParameters().size(), is(1)); assertThat(serviceBean.getParameters().get("service-paramA"), is("service-paramA")); } @Test void testDelayFixedTime() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:/" + resourcePath + "/delay-fixed-time.xml"); ctx.start(); assertThat(ctx.getBean(ServiceBean.class).getDelay(), is(300)); } @Test void testTimeoutConfig() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/provider-nested-service.xml"); ctx.start(); ModuleConfigManager configManager = ApplicationModel.defaultModel().getDefaultModule().getConfigManager(); Collection<ProviderConfig> providerConfigs = configManager.getProviders(); Assertions.assertEquals(2, providerConfigs.size()); ProviderConfig defaultProvider = configManager.getDefaultProvider().get(); assertThat(defaultProvider.getTimeout(), is(2000)); ProviderConfig provider2 = configManager.getProvider("provider2").get(); ServiceConfigBase<Object> serviceConfig2 = configManager.getService("serviceConfig2"); Assertions.assertEquals(1000, provider2.getTimeout()); Assertions.assertEquals(provider2.getTimeout(), serviceConfig2.getTimeout()); } @Test void testMonitor() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/provider-with-monitor.xml"); ctx.start(); assertThat(ctx.getBean(MonitorConfig.class), not(nullValue())); } // @Test // public void testMultiMonitor() { // Assertions.assertThrows(BeanCreationException.class, () -> { // ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + // "/multi-monitor.xml"); // ctx.start(); // }); // } // // @Test // public void testMultiProviderConfig() { // Assertions.assertThrows(BeanCreationException.class, () -> { // ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + // "/provider-multi.xml"); // ctx.start(); // }); // } @Test void testModuleInfo() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/provider-with-module.xml"); ctx.start(); ModuleConfig moduleConfig = ctx.getBean(ModuleConfig.class); assertThat(moduleConfig.getName(), is("test-module")); } @Test void testNotificationWithWrongBean() { Assertions.assertThrows(BeanCreationException.class, () -> { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/consumer-notification.xml"); ctx.start(); }); } @Test void testProperty() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/service-class.xml"); ctx.start(); ServiceBean serviceBean = ctx.getBean(ServiceBean.class); String prefix = ((DemoServiceImpl) serviceBean.getRef()).getPrefix(); assertThat(prefix, is("welcome:")); } @Test void testMetricsAggregation() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/metrics-aggregation.xml"); ctx.start(); ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); MetricsConfig metricsBean = ctx.getBean(MetricsConfig.class); MetricsConfig metrics = configManager.getMetrics().get(); assertTrue(metrics.getEnableJvm()); assertEquals(metrics.getAggregation().getEnabled(), true); assertEquals(metrics.getAggregation().getBucketNum(), 5); assertEquals(metrics.getAggregation().getTimeWindowSeconds(), 120); assertEquals( metrics.getAggregation().getEnabled(), metricsBean.getAggregation().getEnabled()); assertEquals( metrics.getAggregation().getBucketNum(), metricsBean.getAggregation().getBucketNum()); assertEquals( metrics.getAggregation().getTimeWindowSeconds(), metricsBean.getAggregation().getTimeWindowSeconds()); } @Test void testMetricsPrometheus() { SysProps.setProperty("dubbo.metrics.enabled", "true"); SysProps.setProperty("dubbo.metrics.protocol", "prometheus"); ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(resourcePath + "/metrics-prometheus.xml"); ctx.start(); ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); MetricsConfig metricsBean = ctx.getBean(MetricsConfig.class); MetricsConfig metrics = configManager.getMetrics().get(); assertEquals(metrics.getProtocol(), PROTOCOL_PROMETHEUS); assertEquals(metrics.getPrometheus().getExporter().getEnabled(), true); assertEquals(metrics.getPrometheus().getExporter().getEnableHttpServiceDiscovery(), true); assertEquals(metrics.getPrometheus().getExporter().getHttpServiceDiscoveryUrl(), "localhost:8080"); assertEquals(metrics.getPrometheus().getPushgateway().getEnabled(), true); assertEquals(metrics.getPrometheus().getPushgateway().getBaseUrl(), "localhost:9091"); assertEquals(metrics.getPrometheus().getPushgateway().getPushInterval(), 30); assertEquals(metrics.getPrometheus().getPushgateway().getUsername(), "username"); assertEquals(metrics.getPrometheus().getPushgateway().getPassword(), "password"); assertEquals(metrics.getPrometheus().getPushgateway().getJob(), "job"); assertEquals(metricsBean.getProtocol(), PROTOCOL_PROMETHEUS); assertEquals(metricsBean.getPrometheus().getExporter().getEnabled(), true); assertEquals(metricsBean.getPrometheus().getExporter().getEnableHttpServiceDiscovery(), true); assertEquals(metricsBean.getPrometheus().getExporter().getHttpServiceDiscoveryUrl(), "localhost:8080"); assertEquals(metricsBean.getPrometheus().getPushgateway().getEnabled(), true); assertEquals(metricsBean.getPrometheus().getPushgateway().getBaseUrl(), "localhost:9091"); assertEquals(metricsBean.getPrometheus().getPushgateway().getPushInterval(), 30); assertEquals(metricsBean.getPrometheus().getPushgateway().getUsername(), "username"); assertEquals(metricsBean.getPrometheus().getPushgateway().getPassword(), "password"); assertEquals(metricsBean.getPrometheus().getPushgateway().getJob(), "job"); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/KeepRunningOnSpringClosedTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/KeepRunningOnSpringClosedTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context; import org.apache.dubbo.common.deploy.ApplicationDeployer; import org.apache.dubbo.common.deploy.DeployState; import org.apache.dubbo.common.deploy.ModuleDeployer; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.DubboStateListener; import org.apache.dubbo.config.spring.SysProps; import org.apache.dubbo.rpc.model.ModuleModel; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; class KeepRunningOnSpringClosedTest { @Test void test() { // set KeepRunningOnSpringClosed flag for next spring context DubboSpringInitCustomizerHolder.get().addCustomizer(context -> { context.setKeepRunningOnSpringClosed(true); }); ClassPathXmlApplicationContext providerContext = null; try { String resourcePath = "org/apache/dubbo/config/spring"; providerContext = new ClassPathXmlApplicationContext( resourcePath + "/demo-provider.xml", resourcePath + "/demo-provider-properties.xml"); providerContext.start(); // Expect 1: dubbo application state is STARTED after spring context start finish. // No need check and wait DubboStateListener dubboStateListener = providerContext.getBean(DubboStateListener.class); Assertions.assertEquals(DeployState.COMPLETION, dubboStateListener.getState()); ModuleModel moduleModel = providerContext.getBean(ModuleModel.class); ModuleDeployer moduleDeployer = moduleModel.getDeployer(); Assertions.assertTrue(moduleDeployer.isCompletion()); ApplicationDeployer applicationDeployer = moduleModel.getApplicationModel().getDeployer(); Assertions.assertEquals(DeployState.COMPLETION, applicationDeployer.getState()); Assertions.assertTrue(applicationDeployer.isCompletion()); Assertions.assertTrue(applicationDeployer.isStarted()); Assertions.assertFalse(applicationDeployer.isStopped()); Assertions.assertNotNull(DubboSpringInitializer.findBySpringContext(providerContext)); // close spring context providerContext.close(); // Expect 2: dubbo application will not be destroyed after closing spring context cause // setKeepRunningOnSpringClosed(true) Assertions.assertEquals(DeployState.COMPLETION, applicationDeployer.getState()); Assertions.assertTrue(applicationDeployer.isCompletion()); Assertions.assertTrue(applicationDeployer.isStarted()); Assertions.assertFalse(applicationDeployer.isStopped()); Assertions.assertNull(DubboSpringInitializer.findBySpringContext(providerContext)); } finally { DubboBootstrap.getInstance().stop(); SysProps.clear(); if (providerContext != null) { providerContext.close(); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/customize/DubboSpringInitCustomizerTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/customize/DubboSpringInitCustomizerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context.customize; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.SysProps; import org.apache.dubbo.config.spring.api.HelloService; import org.apache.dubbo.config.spring.context.DubboSpringInitCustomizerHolder; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; class DubboSpringInitCustomizerTest { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); SysProps.setProperty("dubbo.registry.address", ZookeeperRegistryCenterConfig.getConnectionAddress()); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); SysProps.clear(); } @Test void testReloadSpringContext() { ClassPathXmlApplicationContext providerContext1 = null; ClassPathXmlApplicationContext providerContext2 = null; ApplicationModel applicationModel = new FrameworkModel().newApplication(); applicationModel.getDefaultModule(); try { // start spring context 1 ModuleModel moduleModel1 = applicationModel.newModule(); DubboSpringInitCustomizerHolder.get().addCustomizer(context -> { context.setModuleModel(moduleModel1); }); providerContext1 = new ClassPathXmlApplicationContext("dubbo-provider-v1.xml", getClass()); ModuleModel moduleModelFromSpring1 = providerContext1.getBean(ModuleModel.class); Assertions.assertSame(moduleModel1, moduleModelFromSpring1); String serviceKey1 = HelloService.class.getName() + ":1.0.0"; ServiceDescriptor serviceDescriptor1 = moduleModelFromSpring1.getServiceRepository().lookupService(serviceKey1); Assertions.assertNotNull(serviceDescriptor1); // close spring context 1 providerContext1.close(); Assertions.assertTrue(moduleModel1.isDestroyed()); Assertions.assertFalse(moduleModel1.getApplicationModel().isDestroyed()); providerContext1 = null; ModuleModel moduleModel2 = applicationModel.newModule(); DubboSpringInitCustomizerHolder.get().addCustomizer(context -> { context.setModuleModel(moduleModel2); }); // load spring context 2 providerContext2 = new ClassPathXmlApplicationContext("dubbo-provider-v2.xml", getClass()); ModuleModel moduleModelFromSpring2 = providerContext2.getBean(ModuleModel.class); Assertions.assertSame(moduleModel2, moduleModelFromSpring2); Assertions.assertNotSame(moduleModelFromSpring1, moduleModelFromSpring2); String serviceKey2 = HelloService.class.getName() + ":2.0.0"; ServiceDescriptor serviceDescriptor2 = moduleModelFromSpring2.getServiceRepository().lookupService(serviceKey2); Assertions.assertNotNull(serviceDescriptor2); Assertions.assertNotSame(serviceDescriptor1, serviceDescriptor2); providerContext2.close(); providerContext2 = null; } finally { if (providerContext1 != null) { providerContext1.close(); } if (providerContext2 != null) { providerContext2.close(); } applicationModel.destroy(); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinderTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context.properties; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD; @ExtendWith(SpringExtension.class) @TestPropertySource(locations = "classpath:/dubbo-binder.properties") @ContextConfiguration(classes = DefaultDubboConfigBinder.class) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD) class DefaultDubboConfigBinderTest { @BeforeAll public static void setUp() { DubboBootstrap.reset(); } @Autowired private DubboConfigBinder dubboConfigBinder; @Test void testBinder() { ApplicationConfig applicationConfig = new ApplicationConfig(); dubboConfigBinder.bind("dubbo.application", applicationConfig); Assertions.assertEquals("hello", applicationConfig.getName()); Assertions.assertEquals("world", applicationConfig.getOwner()); RegistryConfig registryConfig = new RegistryConfig(); dubboConfigBinder.bind("dubbo.registry", registryConfig); Assertions.assertEquals("10.20.153.17", registryConfig.getAddress()); ProtocolConfig protocolConfig = new ProtocolConfig(); dubboConfigBinder.bind("dubbo.protocol", protocolConfig); Assertions.assertEquals(Integer.valueOf(20881), protocolConfig.getPort()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrarTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context.annotation; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.DemoService; import org.apache.dubbo.config.spring.context.annotation.consumer.ConsumerConfiguration; import org.apache.dubbo.config.spring.context.annotation.provider.DemoServiceImpl; import org.apache.dubbo.config.spring.context.annotation.provider.ProviderConfiguration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.aop.support.AopUtils; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.transaction.annotation.Transactional; import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; /** * {@link DubboComponentScanRegistrar} Test * * @since 2.5.8 */ class DubboComponentScanRegistrarTest { @BeforeEach public void setUp() { DubboBootstrap.reset(); } @AfterEach public void tearDown() {} @Test void test() { AnnotationConfigApplicationContext providerContext = new AnnotationConfigApplicationContext(); providerContext.register(ProviderConfiguration.class); providerContext.refresh(); DemoService demoService = providerContext.getBean(DemoService.class); String value = demoService.sayName("Mercy"); Assertions.assertEquals("Hello,Mercy", value); Class<?> beanClass = AopUtils.getTargetClass(demoService); // DemoServiceImpl with @Transactional Assertions.assertEquals(DemoServiceImpl.class, beanClass); // Test @Transactional is present or not Assertions.assertNotNull(findAnnotation(beanClass, Transactional.class)); // consumer app AnnotationConfigApplicationContext consumerContext = new AnnotationConfigApplicationContext(); consumerContext.register(ConsumerConfiguration.class); consumerContext.refresh(); ConsumerConfiguration consumerConfiguration = consumerContext.getBean(ConsumerConfiguration.class); demoService = consumerConfiguration.getDemoService(); value = demoService.sayName("Mercy"); Assertions.assertEquals("Hello,Mercy", value); ConsumerConfiguration.Child child = consumerContext.getBean(ConsumerConfiguration.Child.class); // From Child demoService = child.getDemoServiceFromChild(); Assertions.assertNotNull(demoService); value = demoService.sayName("Mercy"); Assertions.assertEquals("Hello,Mercy", value); // From Parent demoService = child.getDemoServiceFromParent(); Assertions.assertNotNull(demoService); value = demoService.sayName("Mercy"); Assertions.assertEquals("Hello,Mercy", value); // From Ancestor demoService = child.getDemoServiceFromAncestor(); Assertions.assertNotNull(demoService); value = demoService.sayName("Mercy"); Assertions.assertEquals("Hello,Mercy", value); providerContext.close(); consumerContext.close(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context.annotation; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.spring.api.DemoService; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationTestConfiguration; import org.apache.dubbo.config.spring.context.annotation.consumer.test.TestConsumerConfiguration; import org.apache.dubbo.config.spring.context.annotation.provider.DemoServiceImpl; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.aop.support.AopUtils; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.PropertySource; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; /** * {@link EnableDubbo} Test * * @since 2.5.8 */ class EnableDubboTest { private AnnotationConfigApplicationContext context; @BeforeEach public void setUp() { context = new AnnotationConfigApplicationContext(); DubboBootstrap.reset(); } @AfterEach public void tearDown() { context.close(); DubboBootstrap.reset(); } @Test void testProvider() { context.register(TestProviderConfiguration.class); context.refresh(); DemoService demoService = context.getBean(DemoService.class); String value = demoService.sayName("Mercy"); Assertions.assertEquals("Hello,Mercy", value); Class<?> beanClass = AopUtils.getTargetClass(demoService); // DemoServiceImpl with @Transactional Assertions.assertEquals(DemoServiceImpl.class, beanClass); // Test @Transactional is present or not Assertions.assertNotNull(findAnnotation(beanClass, Transactional.class)); } @Test void testConsumer() { context.register(TestProviderConfiguration.class, TestConsumerConfiguration.class); context.refresh(); TestConsumerConfiguration consumerConfiguration = context.getBean(TestConsumerConfiguration.class); DemoService demoService = consumerConfiguration.getDemoService(); String value = demoService.sayName("Mercy"); Assertions.assertEquals("Hello,Mercy", value); DemoService autowiredDemoService = consumerConfiguration.getAutowiredDemoService(); Assertions.assertEquals("Hello,Mercy", autowiredDemoService.sayName("Mercy")); DemoService autowiredReferDemoService = consumerConfiguration.getAutowiredReferDemoService(); Assertions.assertEquals("Hello,Mercy", autowiredReferDemoService.sayName("Mercy")); TestConsumerConfiguration.Child child = context.getBean(TestConsumerConfiguration.Child.class); // From Child demoService = child.getDemoServiceFromChild(); Assertions.assertNotNull(demoService); value = demoService.sayName("Mercy"); Assertions.assertEquals("Hello,Mercy", value); // From Parent // demoService = child.getDemoServiceFromParent(); // // Assertions.assertNotNull(demoService); // // value = demoService.sayName("Mercy"); // // Assertions.assertEquals("Hello,Mercy", value); // From Ancestor demoService = child.getDemoServiceFromAncestor(); Assertions.assertNotNull(demoService); value = demoService.sayName("Mercy"); Assertions.assertEquals("Hello,Mercy", value); // Test my-registry2 bean presentation RegistryConfig registryConfig = context.getBean("my-registry", RegistryConfig.class); // Test multiple binding Assertions.assertEquals("N/A", registryConfig.getAddress()); } @EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.context.annotation.provider") @ComponentScan(basePackages = "org.apache.dubbo.config.spring.context.annotation.provider") @PropertySource("classpath:/META-INF/dubbo-provider.properties") @Import(ServiceAnnotationTestConfiguration.class) @EnableTransactionManagement public static class TestProviderConfiguration { @Primary @Bean public PlatformTransactionManager platformTransactionManager() { return new PlatformTransactionManager() { @Override public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException { return null; } @Override public void commit(TransactionStatus status) throws TransactionException {} @Override public void rollback(TransactionStatus status) throws TransactionException {} }; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context.annotation; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collection; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.PropertySource; import static org.apache.dubbo.config.spring.util.BeanRegistrar.hasAlias; import static org.junit.jupiter.api.Assertions.assertFalse; /** * {@link EnableDubboConfig} Test * * @since 2.5.8 */ class EnableDubboConfigTest { @BeforeEach public void setUp() { DubboBootstrap.reset(); } @AfterEach public void tearDown() { DubboBootstrap.reset(); } // @Test public void testSingle() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(TestConfig.class); context.refresh(); // application ApplicationConfig applicationConfig = context.getBean("applicationBean", ApplicationConfig.class); Assertions.assertEquals("dubbo-demo-application", applicationConfig.getName()); // module ModuleConfig moduleConfig = context.getBean("moduleBean", ModuleConfig.class); Assertions.assertEquals("dubbo-demo-module", moduleConfig.getName()); // registry RegistryConfig registryConfig = context.getBean(RegistryConfig.class); Assertions.assertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress()); // protocol ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.class); Assertions.assertEquals("dubbo", protocolConfig.getName()); Assertions.assertEquals(Integer.valueOf(20880), protocolConfig.getPort()); // monitor MonitorConfig monitorConfig = context.getBean(MonitorConfig.class); Assertions.assertEquals("zookeeper://127.0.0.1:32770", monitorConfig.getAddress()); // provider ProviderConfig providerConfig = context.getBean(ProviderConfig.class); Assertions.assertEquals("127.0.0.1", providerConfig.getHost()); // consumer ConsumerConfig consumerConfig = context.getBean(ConsumerConfig.class); Assertions.assertEquals("netty", consumerConfig.getClient()); // asserts aliases assertFalse(hasAlias(context, "org.apache.dubbo.config.RegistryConfig#0", "zookeeper")); assertFalse(hasAlias(context, "org.apache.dubbo.config.MonitorConfig#0", "zookeeper")); } // @Test public void testMultiple() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(TestMultipleConfig.class); context.refresh(); RegistryConfig registry1 = context.getBean("registry1", RegistryConfig.class); Assertions.assertEquals(2181, registry1.getPort()); RegistryConfig registry2 = context.getBean("registry2", RegistryConfig.class); Assertions.assertEquals(2182, registry2.getPort()); ConfigManager configManager = ApplicationModel.defaultModel().getApplicationConfigManager(); Collection<ProtocolConfig> protocolConfigs = configManager.getProtocols(); Assertions.assertEquals(3, protocolConfigs.size()); configManager.getProtocol("dubbo").get(); configManager.getProtocol("rest").get(); // asserts aliases // assertTrue(hasAlias(context, "applicationBean2", "dubbo-demo-application2")); // assertTrue(hasAlias(context, "applicationBean3", "dubbo-demo-application3")); } @EnableDubboConfig @PropertySource("META-INF/config.properties") private static class TestMultipleConfig {} @EnableDubboConfig(multiple = false) @PropertySource("META-INF/config.properties") private static class TestConfig {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context.annotation; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import java.io.IOException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.io.support.ResourcePropertySource; /** * {@link DubboConfigConfiguration} Test * * @since 2.5.8 */ class DubboConfigConfigurationTest { private AnnotationConfigApplicationContext context; @BeforeEach public void before() throws IOException { DubboBootstrap.reset(); context = new AnnotationConfigApplicationContext(); ResourcePropertySource propertySource = new ResourcePropertySource("META-INF/config.properties"); context.getEnvironment().getPropertySources().addFirst(propertySource); } @AfterEach public void after() { context.close(); } @Test void testSingle() throws IOException { context.register(DubboConfigConfiguration.Single.class); context.refresh(); // application ApplicationConfig applicationConfig = context.getBean("applicationBean", ApplicationConfig.class); Assertions.assertEquals("dubbo-demo-application", applicationConfig.getName()); // module ModuleConfig moduleConfig = context.getBean("moduleBean", ModuleConfig.class); Assertions.assertEquals("dubbo-demo-module", moduleConfig.getName()); // registry RegistryConfig registryConfig = context.getBean(RegistryConfig.class); Assertions.assertEquals("zookeeper://192.168.99.100:32770", registryConfig.getAddress()); // protocol ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.class); Assertions.assertEquals("dubbo", protocolConfig.getName()); Assertions.assertEquals(Integer.valueOf(20880), protocolConfig.getPort()); } @Test void testMultiple() { context.register(DubboConfigConfiguration.Multiple.class); context.refresh(); RegistryConfig registry1 = context.getBean("registry1", RegistryConfig.class); Assertions.assertEquals(2181, registry1.getPort()); RegistryConfig registry2 = context.getBean("registry2", RegistryConfig.class); Assertions.assertEquals(2182, registry2.getPort()); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/ProviderConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context.annotation.provider; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.PropertySource; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.support.AbstractPlatformTransactionManager; import org.springframework.transaction.support.DefaultTransactionStatus; @DubboComponentScan(basePackages = "org.apache.dubbo.config.spring.context.annotation.provider") @PropertySource("classpath:/META-INF/default.properties") @EnableTransactionManagement public class ProviderConfiguration { /** * Current application configuration, to replace XML config: * <prev> * &lt;dubbo:application name="dubbo-demo-application"/&gt; * </prev> * * @return {@link ApplicationConfig} Bean */ @Bean("dubbo-demo-application") public ApplicationConfig applicationConfig() { ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("dubbo-demo-application"); return applicationConfig; } /** * Current registry center configuration, to replace XML config: * <prev> * &lt;dubbo:registry id="my-registry" address="N/A"/&gt; * </prev> * * @return {@link RegistryConfig} Bean */ @Bean("my-registry") public RegistryConfig registryConfig() { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress("N/A"); return registryConfig; } /** * Current protocol configuration, to replace XML config: * <prev> * &lt;dubbo:protocol name="dubbo" port="12345"/&gt; * </prev> * * @return {@link ProtocolConfig} Bean */ @Bean("dubbo") public ProtocolConfig protocolConfig() { ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setName("dubbo"); protocolConfig.setPort(12345); return protocolConfig; } @Primary @Bean public PlatformTransactionManager platformTransactionManager() { return new AbstractPlatformTransactionManager() { private Logger logger = LoggerFactory.getLogger("TestPlatformTransactionManager"); @Override protected Object doGetTransaction() throws TransactionException { String transaction = "transaction_" + UUID.randomUUID().toString(); logger.info("Create transaction: " + transaction); return transaction; } @Override protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException { logger.info("Begin transaction: " + transaction); } @Override protected void doCommit(DefaultTransactionStatus status) throws TransactionException { logger.info("Commit transaction: " + status.getTransaction()); } @Override protected void doRollback(DefaultTransactionStatus status) throws TransactionException { logger.info("Rollback transaction: " + status.getTransaction()); } }; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DemoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context.annotation.provider; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.spring.api.Box; import org.apache.dubbo.config.spring.api.DemoService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * {@link DemoService} Service implementation * * @since 2.5.8 */ @org.apache.dubbo.config.annotation.Service( version = "2.5.7", application = "${demo.service.application}", protocol = "${demo.service.protocol}", registry = "${demo.service.registry}", methods = @Method(timeout = 100, name = "sayName")) @Service @Transactional public class DemoServiceImpl implements DemoService { @Override public String sayName(String name) { return "Hello," + name; } @Override public Box getBox() { throw new UnsupportedOperationException("For Purposes!"); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/HelloServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context.annotation.provider; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.spring.api.HelloService; /** * {@link HelloService} Implementation just annotating Dubbo's {@link Service} * * @since 2.5.9 */ @Service(interfaceName = "org.apache.dubbo.config.spring.api.HelloService", version = "2") public class HelloServiceImpl implements HelloService { @Override public String sayHello(String name) { return "Hello, " + name; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/provider/DefaultHelloService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context.annotation.provider; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.spring.api.HelloService; import org.springframework.stereotype.Service; /** * Default {@link HelloService} annotation with Spring's {@link Service} * and Dubbo's {@link org.apache.dubbo.config.annotation.Service} * */ @Service @DubboService public class DefaultHelloService implements HelloService { @Override public String sayHello(String name) { return "Greeting, " + name; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/ConsumerConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context.annotation.consumer; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.spring.api.DemoService; import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration("consumerConfiguration") @DubboComponentScan(basePackageClasses = ConsumerConfiguration.class) @PropertySource("META-INF/default.properties") public class ConsumerConfiguration { private static final String remoteURL = "dubbo://127.0.0.1:12345?version=2.5.7"; /** * Current application configuration, to replace XML config: * <prev> * &lt;dubbo:application name="dubbo-demo-application"/&gt; * </prev> * * @return {@link ApplicationConfig} Bean */ @Bean("dubbo-demo-application") public ApplicationConfig applicationConfig() { ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("dubbo-demo-application"); return applicationConfig; } /** * Current registry center configuration, to replace XML config: * <prev> * &lt;dubbo:registry address="N/A"/&gt; * </prev> * * @return {@link RegistryConfig} Bean */ @Bean public RegistryConfig registryConfig() { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress("N/A"); return registryConfig; } @Autowired private DemoService demoServiceFromAncestor; @Reference(version = "2.5.7", url = remoteURL) private DemoService demoService; public DemoService getDemoService() { return demoService; } public void setDemoService(DemoService demoService) { this.demoService = demoService; } @Bean public Child c() { return new Child(); } public abstract static class Ancestor { @Reference(version = "2.5.7", url = remoteURL) private DemoService demoServiceFromAncestor; public DemoService getDemoServiceFromAncestor() { return demoServiceFromAncestor; } public void setDemoServiceFromAncestor(DemoService demoServiceFromAncestor) { this.demoServiceFromAncestor = demoServiceFromAncestor; } } public abstract static class Parent extends Ancestor { private DemoService demoServiceFromParent; public DemoService getDemoServiceFromParent() { return demoServiceFromParent; } @Reference(version = "2.5.7", url = remoteURL) public void setDemoServiceFromParent(DemoService demoServiceFromParent) { this.demoServiceFromParent = demoServiceFromParent; } } public static class Child extends Parent { @Autowired private DemoService demoService; @Reference(version = "2.5.7", url = remoteURL) private DemoService demoServiceFromChild; public DemoService getDemoService() { return demoService; } public DemoService getDemoServiceFromChild() { return demoServiceFromChild; } public void setDemoServiceFromChild(DemoService demoServiceFromChild) { this.demoServiceFromChild = demoServiceFromChild; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/context/annotation/consumer/test/TestConsumerConfiguration.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.context.annotation.consumer.test; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.spring.api.DemoService; import org.apache.dubbo.config.spring.context.annotation.EnableDubbo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * Test Consumer Configuration * * @since 2.5.7 */ @EnableDubbo(scanBasePackageClasses = TestConsumerConfiguration.class) @PropertySource("classpath:/META-INF/dubbb-consumer.properties") @EnableTransactionManagement public class TestConsumerConfiguration { private static final String remoteURL = "dubbo://127.0.0.1:12345?version=2.5.7"; @Reference( id = "demoService", version = "2.5.7", url = remoteURL, application = "dubbo-demo-application", filter = "mymock") private DemoService demoService; @Autowired @Qualifier("demoServiceImpl") private DemoService autowiredDemoService; @Autowired @Qualifier("demoService") private DemoService autowiredReferDemoService; public DemoService getAutowiredDemoService() { return autowiredDemoService; } public DemoService getAutowiredReferDemoService() { return autowiredReferDemoService; } public DemoService getDemoService() { return demoService; } public void setDemoService(DemoService demoService) { this.demoService = demoService; } @Bean public Child c() { return new Child(); } public abstract static class Ancestor { @DubboReference(version = "2.5.7", url = remoteURL, filter = "mymock", application = "dubbo-demo-application") private DemoService demoServiceFromAncestor; public DemoService getDemoServiceFromAncestor() { return demoServiceFromAncestor; } public void setDemoServiceFromAncestor(DemoService demoServiceFromAncestor) { this.demoServiceFromAncestor = demoServiceFromAncestor; } } public static class Child extends Ancestor { @Reference(version = "2.5.7", url = remoteURL, filter = "mymock", application = "dubbo-demo-application") private DemoService demoServiceFromChild; public DemoService getDemoServiceFromChild() { return demoServiceFromChild; } public void setDemoServiceFromChild(DemoService demoServiceFromChild) { this.demoServiceFromChild = demoServiceFromChild; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring; import org.apache.dubbo.common.aot.NativeDetector; import org.apache.dubbo.common.bytecode.Proxy; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.spring.aot.AotWithSpringDetector; import org.apache.dubbo.config.spring.context.DubboConfigApplicationListener; import org.apache.dubbo.config.spring.context.DubboConfigBeanInitializer; import org.apache.dubbo.config.spring.reference.ReferenceAttributes; import org.apache.dubbo.config.spring.reference.ReferenceBeanManager; import org.apache.dubbo.config.spring.reference.ReferenceBeanSupport; import org.apache.dubbo.config.spring.schema.DubboBeanDefinitionParser; import org.apache.dubbo.config.spring.util.LazyTargetInvocationHandler; import org.apache.dubbo.config.spring.util.LazyTargetSource; import org.apache.dubbo.config.spring.util.LockUtils; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.rpc.proxy.AbstractProxyFactory; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED; /** * <p> * Spring FactoryBean for {@link ReferenceConfig}. * </p> * * * <p></p> * Step 1: Register ReferenceBean in Java-config class: * <pre class="code"> * &#64;Configuration * public class ReferenceConfiguration { * &#64;Bean * &#64;DubboReference(group = "demo") * public ReferenceBean&lt;HelloService&gt; helloService() { * return new ReferenceBean(); * } * * // As GenericService * &#64;Bean * &#64;DubboReference(group = "demo", interfaceClass = HelloService.class) * public ReferenceBean&lt;GenericService&gt; genericHelloService() { * return new ReferenceBean(); * } * } * </pre> * <p> * Or register ReferenceBean in xml: * <pre class="code"> * &lt;dubbo:reference id="helloService" interface="org.apache.dubbo.config.spring.api.HelloService"/&gt; * &lt;!-- As GenericService --&gt; * &lt;dubbo:reference id="genericHelloService" interface="org.apache.dubbo.config.spring.api.HelloService" generic="true"/&gt; * </pre> * <p> * Step 2: Inject ReferenceBean by @Autowired * <pre class="code"> * public class FooController { * &#64;Autowired * private HelloService helloService; * * &#64;Autowired * private GenericService genericHelloService; * } * </pre> * * @see org.apache.dubbo.config.annotation.DubboReference * @see org.apache.dubbo.config.spring.reference.ReferenceBeanBuilder */ public class ReferenceBean<T> implements FactoryBean<T>, ApplicationContextAware, BeanClassLoaderAware, BeanNameAware, InitializingBean, DisposableBean { private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private transient ApplicationContext applicationContext; private ClassLoader beanClassLoader; // lazy proxy of reference private Object lazyProxy; // beanName protected String id; // reference key private String key; /** * The interface class of the reference service */ private Class<?> interfaceClass; /* * remote service interface class name */ // 'interfaceName' field for compatible with seata-1.4.0: // io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc() private String interfaceName; // proxy style private String proxy; // from annotation attributes private Map<String, Object> referenceProps; // from xml bean definition private MutablePropertyValues propertyValues; // actual reference config private volatile ReferenceConfig referenceConfig; // ReferenceBeanManager private ReferenceBeanManager referenceBeanManager; // Registration sources of this reference, may be xml file or annotation location private List<Map<String, Object>> sources = new ArrayList<>(); public ReferenceBean() { super(); } public ReferenceBean(Map<String, Object> referenceProps) { this.referenceProps = referenceProps; } @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } @Override public void setBeanName(String name) { this.setId(name); } /** * Create bean instance. * * <p></p> * Why we need a lazy proxy? * <p> * <p/> * When Spring searches beans by type, if Spring cannot determine the type of a factory bean, it may try to initialize it. * The ReferenceBean is also a FactoryBean. * <br/> * (This has already been resolved by decorating the BeanDefinition: {@link DubboBeanDefinitionParser#configReferenceBean}) * <p> * <p/> * In addition, if some ReferenceBeans are dependent on beans that are initialized very early, * and dubbo config beans are not ready yet, there will be many unexpected problems if initializing the dubbo reference immediately. * <p> * <p/> * When it is initialized, only a lazy proxy object will be created, * and dubbo reference-related resources will not be initialized. * <br/> * In this way, the influence of Spring is eliminated, and the dubbo configuration initialization is controllable. * * @see DubboConfigBeanInitializer * @see ReferenceBeanManager#initReferenceBean(ReferenceBean) * @see DubboBeanDefinitionParser#configReferenceBean */ @Override public T getObject() { if (lazyProxy == null) { createLazyProxy(); } return (T) lazyProxy; } @Override public Class<?> getObjectType() { return getInterfaceClass(); } @Override @Parameter(excluded = true) public boolean isSingleton() { return true; } @Override public void afterPropertiesSet() throws Exception { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // pre init xml reference bean or @DubboReference annotation Assert.notEmptyString(getId(), "The id of ReferenceBean cannot be empty"); BeanDefinition beanDefinition = beanFactory.getBeanDefinition(getId()); if (AotWithSpringDetector.useGeneratedArtifacts()) { this.interfaceClass = (Class<?>) beanDefinition.getPropertyValues().get(ReferenceAttributes.INTERFACE_CLASS); this.interfaceName = (String) beanDefinition.getPropertyValues().get(ReferenceAttributes.INTERFACE_NAME); } else { this.interfaceClass = (Class<?>) beanDefinition.getAttribute(ReferenceAttributes.INTERFACE_CLASS); this.interfaceName = (String) beanDefinition.getAttribute(ReferenceAttributes.INTERFACE_NAME); } Assert.notNull(this.interfaceClass, "The interface class of ReferenceBean is not initialized"); if (beanDefinition.hasAttribute(Constants.REFERENCE_PROPS)) { // @DubboReference annotation at java-config class @Bean method // @DubboReference annotation at reference field or setter method referenceProps = (Map<String, Object>) beanDefinition.getAttribute(Constants.REFERENCE_PROPS); } else { if (beanDefinition instanceof AnnotatedBeanDefinition) { // Return ReferenceBean in java-config class @Bean method if (referenceProps == null) { referenceProps = new LinkedHashMap<>(); } ReferenceBeanSupport.convertReferenceProps(referenceProps, interfaceClass); if (this.interfaceName == null) { this.interfaceName = (String) referenceProps.get(ReferenceAttributes.INTERFACE); } } else { // xml reference bean propertyValues = beanDefinition.getPropertyValues(); } } if (referenceProps != null) { this.proxy = (String) referenceProps.get(ReferenceAttributes.PROXY); } Assert.notNull(this.interfaceName, "The interface name of ReferenceBean is not initialized"); this.referenceBeanManager = beanFactory.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); referenceBeanManager.addReference(this); } private ConfigurableListableBeanFactory getBeanFactory() { return (ConfigurableListableBeanFactory) applicationContext.getAutowireCapableBeanFactory(); } @Override public void destroy() { // do nothing } public String getId() { return id; } public void setId(String id) { this.id = id; } /** * The interface of this ReferenceBean, for injection purpose * * @return */ public Class<?> getInterfaceClass() { // Compatible with seata-1.4.0: io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc() return interfaceClass; } /** * The interface of remote service */ public String getServiceInterface() { return interfaceName; } /** * The group of the service */ public String getGroup() { // Compatible with seata-1.4.0: io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc() return referenceConfig.getGroup(); } /** * The version of the service */ public String getVersion() { // Compatible with seata-1.4.0: io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc() return referenceConfig.getVersion(); } public String getKey() { return key; } public Map<String, Object> getReferenceProps() { return referenceProps; } public MutablePropertyValues getPropertyValues() { return propertyValues; } public ReferenceConfig getReferenceConfig() { return referenceConfig; } public void setKeyAndReferenceConfig(String key, ReferenceConfig referenceConfig) { this.key = key; this.referenceConfig = referenceConfig; } /** * Create lazy proxy for reference. */ private void createLazyProxy() { // set proxy interfaces // see also: org.apache.dubbo.rpc.proxy.AbstractProxyFactory.getProxy(org.apache.dubbo.rpc.Invoker<T>, boolean) List<Class<?>> interfaces = new ArrayList<>(); interfaces.add(interfaceClass); Class<?>[] internalInterfaces = AbstractProxyFactory.getInternalInterfaces(); Collections.addAll(interfaces, internalInterfaces); if (!StringUtils.isEquals(interfaceClass.getName(), interfaceName)) { // add service interface try { Class<?> serviceInterface = ClassUtils.forName(interfaceName, beanClassLoader); interfaces.add(serviceInterface); } catch (ClassNotFoundException e) { // generic call maybe without service interface class locally } } if (NativeDetector.inNativeImage()) { generateFromJdk(interfaces); } if (this.lazyProxy == null && (StringUtils.isEmpty(this.proxy) || CommonConstants.DEFAULT_PROXY.equalsIgnoreCase(this.proxy))) { generateFromJavassistFirst(interfaces); } if (this.lazyProxy == null) { generateFromJdk(interfaces); } } private void generateFromJavassistFirst(List<Class<?>> interfaces) { try { this.lazyProxy = Proxy.getProxy(interfaces.toArray(new Class[0])) .newInstance(new LazyTargetInvocationHandler(new DubboReferenceLazyInitTargetSource())); } catch (Throwable fromJavassist) { // try fall back to JDK proxy factory try { this.lazyProxy = java.lang.reflect.Proxy.newProxyInstance( beanClassLoader, interfaces.toArray(new Class[0]), new LazyTargetInvocationHandler(new DubboReferenceLazyInitTargetSource())); logger.error( PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy success. " + "Interfaces: " + interfaces, fromJavassist); } catch (Throwable fromJdk) { logger.error( PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + interfaces + " Javassist Error.", fromJavassist); logger.error( PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + interfaces + " JDK Error.", fromJdk); throw fromJavassist; } } } private void generateFromJdk(List<Class<?>> interfaces) { try { this.lazyProxy = java.lang.reflect.Proxy.newProxyInstance( beanClassLoader, interfaces.toArray(new Class[0]), new LazyTargetInvocationHandler(new DubboReferenceLazyInitTargetSource())); } catch (Throwable fromJdk) { logger.error( PROXY_FAILED, "", "", "Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. " + "Interfaces: " + interfaces + " JDK Error.", fromJdk); throw fromJdk; } } private Object getCallProxy() throws Exception { if (referenceConfig == null) { synchronized (LockUtils.getSingletonMutex(applicationContext)) { if (referenceConfig == null) { referenceBeanManager.initReferenceBean(this); applicationContext .getBean( DubboConfigApplicationListener.class.getName(), DubboConfigApplicationListener.class) .init(); logger.warn( CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "ReferenceBean is not ready yet, please make sure to " + "call reference interface method after dubbo is started."); } } } // get reference proxy // Subclasses should synchronize on the given Object if they perform any sort of extended singleton creation // phase. // In particular, subclasses should not have their own mutexes involved in singleton creation, to avoid the // potential for deadlocks in lazy-init situations. // The redundant type cast is to be compatible with earlier than spring-4.2 if (referenceConfig.configInitialized()) { return referenceConfig.get(); } synchronized (LockUtils.getSingletonMutex(applicationContext)) { return referenceConfig.get(); } } private class DubboReferenceLazyInitTargetSource implements LazyTargetSource { @Override public Object getTarget() throws Exception { return getCallProxy(); } } public void setInterfaceClass(Class<?> interfaceClass) { this.interfaceClass = interfaceClass; } public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } /** * It is only used in native scenarios to get referenceProps * because attribute is not passed by BeanDefinition by default. * @param referencePropsJson */ public void setReferencePropsJson(String referencePropsJson) { if (StringUtils.isNotEmpty(referencePropsJson)) { this.referenceProps = JsonUtils.toJavaObject(referencePropsJson, Map.class); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertySource; /** * Starting from 2.7.0+, export and refer will only be executed when Spring is fully initialized. * <p> * Each Config bean will get refreshed on the start of the exporting and referring process. * <p> * So it's ok for this bean not to be the first Dubbo Config bean being initialized. * <p> */ public class ConfigCenterBean extends ConfigCenterConfig implements ApplicationContextAware, DisposableBean, EnvironmentAware { private transient ApplicationContext applicationContext; private Boolean includeSpringEnv = false; public ConfigCenterBean() {} public ConfigCenterBean(ApplicationModel applicationModel) { super(applicationModel); } @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public void destroy() throws Exception {} @Override public void setEnvironment(Environment environment) { if (includeSpringEnv) { // Get PropertySource mapped to 'dubbo.properties' in Spring Environment. setExternalConfig(getConfigurations(getConfigFile(), environment)); // Get PropertySource mapped to 'application.dubbo.properties' in Spring Environment. setAppExternalConfig(getConfigurations( StringUtils.isNotEmpty(getAppConfigFile()) ? getAppConfigFile() : ("application." + getConfigFile()), environment)); } } private Map<String, String> getConfigurations(String key, Environment environment) { Object rawProperties = environment.getProperty(key, Object.class); Map<String, String> externalProperties = new HashMap<>(); try { if (rawProperties instanceof Map) { externalProperties.putAll((Map<String, String>) rawProperties); } else if (rawProperties instanceof String) { externalProperties.putAll(ConfigurationUtils.parseProperties((String) rawProperties)); } if (environment instanceof ConfigurableEnvironment && externalProperties.isEmpty()) { ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment) environment; PropertySource propertySource = configurableEnvironment.getPropertySources().get(key); if (propertySource != null) { Object source = propertySource.getSource(); if (source instanceof Map) { ((Map<String, Object>) source).forEach((k, v) -> { externalProperties.put(k, (String) v); }); } } } } catch (Exception e) { throw new IllegalStateException(e); } return externalProperties; } public ApplicationContext getApplicationContext() { return applicationContext; } public Boolean getIncludeSpringEnv() { return includeSpringEnv; } public void setIncludeSpringEnv(Boolean includeSpringEnv) { this.includeSpringEnv = includeSpringEnv; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/SpringScopeModelInitializer.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/SpringScopeModelInitializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ScopeModelInitializer; /** * Register scope beans in spring module */ public class SpringScopeModelInitializer implements ScopeModelInitializer { @Override public void initializeFrameworkModel(FrameworkModel frameworkModel) {} @Override public void initializeApplicationModel(ApplicationModel applicationModel) {} @Override public void initializeModuleModel(ModuleModel moduleModel) {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.spring.context.event.ServiceBeanExportedEvent; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.rpc.model.ModuleModel; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; /** * ServiceFactoryBean * * @export */ public class ServiceBean<T> extends ServiceConfig<T> implements InitializingBean, DisposableBean, ApplicationContextAware, BeanNameAware, ApplicationEventPublisherAware { private static final long serialVersionUID = 213195494150089726L; private final transient Service service; private transient ApplicationContext applicationContext; private transient String beanName; private ApplicationEventPublisher applicationEventPublisher; @Autowired public ServiceBean(ModuleModel moduleModel) { super(moduleModel); this.service = null; } public ServiceBean(ApplicationContext applicationContext) { super(); this.service = null; this.applicationContext = applicationContext; this.setScopeModel(DubboBeanUtils.getModuleModel(applicationContext)); } public ServiceBean(ApplicationContext applicationContext, ModuleModel moduleModel) { super(moduleModel); this.service = null; this.applicationContext = applicationContext; } public ServiceBean(ApplicationContext applicationContext, Service service) { super(service); this.service = service; this.applicationContext = applicationContext; this.setScopeModel(DubboBeanUtils.getModuleModel(applicationContext)); } public ServiceBean(ApplicationContext applicationContext, ModuleModel moduleModel, Service service) { super(moduleModel, service); this.service = service; this.applicationContext = applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override public void setBeanName(String name) { this.beanName = name; } /** * Gets associated {@link Service} * * @return associated {@link Service} */ public Service getService() { return service; } @Override public void afterPropertiesSet() throws Exception { if (StringUtils.isEmpty(getPath())) { if (StringUtils.isNotEmpty(getInterface())) { setPath(getInterface()); } } // register service bean ModuleModel moduleModel = DubboBeanUtils.getModuleModel(applicationContext); moduleModel.getConfigManager().addService(this); moduleModel.getDeployer().setPending(); } /** * Get the name of {@link ServiceBean} * * @return {@link ServiceBean}'s name * @since 2.6.5 */ @Parameter(excluded = true, attribute = false) public String getBeanName() { return this.beanName; } /** * @since 2.6.5 */ @Override protected void exported() { super.exported(); // Publish ServiceBeanExportedEvent publishExportEvent(); } /** * @since 2.6.5 */ private void publishExportEvent() { ServiceBeanExportedEvent exportEvent = new ServiceBeanExportedEvent(this); applicationEventPublisher.publishEvent(exportEvent); } @Override public void destroy() throws Exception { // no need to call unexport() here, see // org.apache.dubbo.config.spring.extension.SpringExtensionInjector.ShutdownHookListener } // merged from dubbox @Override protected Class getServiceClass(T ref) { if (AopUtils.isAopProxy(ref)) { return AopUtils.getTargetClass(ref); } return super.getServiceClass(ref); } /** * @param applicationEventPublisher * @since 2.6.5 */ @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/Constants.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring; /** * Constants of dubbo spring config */ public interface Constants { /** * attributes of reference annotation */ String REFERENCE_PROPS = "referenceProps"; /** * Registration sources of the reference, may be xml file or annotation location */ String REFERENCE_SOURCES = "referenceSources"; /** * The name of an attribute that can be * {@link org.springframework.core.AttributeAccessor#setAttribute set} on a * {@link org.springframework.beans.factory.config.BeanDefinition} so that * factory beans can signal their object type when it can't be deduced from * the factory bean class. * <p/> * From FactoryBean.OBJECT_TYPE_ATTRIBUTE of Spring 5.2. */ String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LazyTargetSource.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LazyTargetSource.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; public interface LazyTargetSource { Object getTarget() throws Exception; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/BeanRegistrar.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/BeanRegistrar.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import org.springframework.core.AliasRegistry; import static org.springframework.util.ObjectUtils.containsElement; import static org.springframework.util.StringUtils.hasText; /** * Bean Registrar */ public abstract class BeanRegistrar { /** * Detect the alias is present or not in the given bean name from {@link AliasRegistry} * * @param registry {@link AliasRegistry} * @param beanName the bean name * @param alias alias to test * @return if present, return <code>true</code>, or <code>false</code> */ public static boolean hasAlias(AliasRegistry registry, String beanName, String alias) { return hasText(beanName) && hasText(alias) && containsElement(registry.getAliases(beanName), alias); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/ObjectUtils.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/ObjectUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; /** * Object Utilities */ @SuppressWarnings("unchecked") public abstract class ObjectUtils { /** * Empty String array */ public static final String[] EMPTY_STRING_ARRAY = {}; /** * Convert from variable arguments to array * * @param values variable arguments * @param <T> The class * @return array */ public static <T> T[] of(T... values) { return values; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LockUtils.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LockUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import java.lang.reflect.Method; import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry; import org.springframework.context.ApplicationContext; public class LockUtils { private static final String DUBBO_SINGLETON_MUTEX_KEY = "DUBBO_SINGLETON_MUTEX"; /** * Get the mutex to lock the singleton in the specified {@link ApplicationContext} */ public static synchronized Object getSingletonMutex(ApplicationContext applicationContext) { DefaultSingletonBeanRegistry autowireCapableBeanFactory = (DefaultSingletonBeanRegistry) applicationContext.getAutowireCapableBeanFactory(); try { return autowireCapableBeanFactory.getSingletonMutex(); } catch (Throwable t1) { try { // try protected Method method = DefaultSingletonBeanRegistry.class.getDeclaredMethod("getSingletonMutex"); method.setAccessible(true); return method.invoke(autowireCapableBeanFactory); } catch (Throwable t2) { // Before Spring 4.2, there is no getSingletonMutex method if (!autowireCapableBeanFactory.containsSingleton(DUBBO_SINGLETON_MUTEX_KEY)) { autowireCapableBeanFactory.registerSingleton(DUBBO_SINGLETON_MUTEX_KEY, new Object()); } return autowireCapableBeanFactory.getSingleton(DUBBO_SINGLETON_MUTEX_KEY); } } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboBeanUtils.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboBeanUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import org.apache.dubbo.config.context.ConfigManager; import org.apache.dubbo.config.spring.beans.factory.annotation.DubboConfigAliasPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServicePackagesHolder; import org.apache.dubbo.config.spring.beans.factory.config.DubboConfigDefaultPropertyValueBeanPostProcessor; import org.apache.dubbo.config.spring.context.DubboConfigApplicationListener; import org.apache.dubbo.config.spring.context.DubboConfigBeanInitializer; import org.apache.dubbo.config.spring.context.DubboContextPostProcessor; import org.apache.dubbo.config.spring.context.DubboDeployApplicationListener; import org.apache.dubbo.config.spring.context.DubboInfraBeanRegisterPostProcessor; import org.apache.dubbo.config.spring.context.DubboSpringInitContext; import org.apache.dubbo.config.spring.reference.ReferenceBeanManager; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.AbstractBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.ApplicationContext; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; /** * Dubbo Bean utilities class * * @since 2.7.6 */ public interface DubboBeanUtils { Log log = LogFactory.getLog(DubboBeanUtils.class); /** * Register the common beans * * @param registry {@link BeanDefinitionRegistry} * @see ReferenceAnnotationBeanPostProcessor * @see DubboConfigDefaultPropertyValueBeanPostProcessor * @see DubboConfigAliasPostProcessor */ static void registerCommonBeans(BeanDefinitionRegistry registry) { registerInfrastructureBean(registry, ServicePackagesHolder.BEAN_NAME, ServicePackagesHolder.class); registerInfrastructureBean(registry, DubboContextPostProcessor.BEAN_NAME, DubboContextPostProcessor.class); registerInfrastructureBean(registry, ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); // Since 2.5.7 Register @Reference Annotation Bean Processor as an infrastructure Bean registerInfrastructureBean( registry, SpringCompatUtils.referenceAnnotationBeanPostProcessor().getName(), SpringCompatUtils.referenceAnnotationBeanPostProcessor()); // TODO Whether DubboConfigAliasPostProcessor can be removed ? // Since 2.7.4 [Feature] https://github.com/apache/dubbo/issues/5093 registerInfrastructureBean( registry, DubboConfigAliasPostProcessor.BEAN_NAME, DubboConfigAliasPostProcessor.class); // register ApplicationListeners registerInfrastructureBean( registry, DubboDeployApplicationListener.class.getName(), DubboDeployApplicationListener.class); registerInfrastructureBean( registry, DubboConfigApplicationListener.class.getName(), DubboConfigApplicationListener.class); // Since 2.7.6 Register DubboConfigDefaultPropertyValueBeanPostProcessor as an infrastructure Bean registerInfrastructureBean( registry, DubboConfigDefaultPropertyValueBeanPostProcessor.BEAN_NAME, DubboConfigDefaultPropertyValueBeanPostProcessor.class); // Dubbo config initializer registerInfrastructureBean(registry, DubboConfigBeanInitializer.BEAN_NAME, DubboConfigBeanInitializer.class); // register infra bean if not exists later registerInfrastructureBean( registry, DubboInfraBeanRegisterPostProcessor.BEAN_NAME, SpringCompatUtils.dubboInfraBeanRegisterPostProcessor()); } /** * Register Infrastructure Bean * * @param beanDefinitionRegistry {@link BeanDefinitionRegistry} * @param beanType the type of bean * @param beanName the name of bean * @return if it's a first time to register, return <code>true</code>, or <code>false</code> */ static boolean registerInfrastructureBean( BeanDefinitionRegistry beanDefinitionRegistry, String beanName, Class<?> beanType) { boolean registered = false; if (!beanDefinitionRegistry.containsBeanDefinition(beanName)) { RootBeanDefinition beanDefinition = new RootBeanDefinition(beanType); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); beanDefinitionRegistry.registerBeanDefinition(beanName, beanDefinition); registered = true; if (log.isDebugEnabled()) { log.debug("The Infrastructure bean definition [" + beanDefinition + "with name [" + beanName + "] has been registered."); } } return registered; } /** * Register a placeholder configurer beans if not exists. * Call this method in BeanDefinitionRegistryPostProcessor, * in order to enable the registered BeanFactoryPostProcessor bean to be loaded and executed. * * @param beanFactory * @param registry * @see DubboInfraBeanRegisterPostProcessor * @see org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.List) */ static void registerPlaceholderConfigurerBeanIfNotExists( ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry) { // Auto register a PropertyPlaceholderConfigurer bean to resolve placeholders with Spring Environment // PropertySources // when loading dubbo xml config with @ImportResource if (!checkBeanExists(beanFactory, PropertySourcesPlaceholderConfigurer.class)) { Map<String, Object> propertySourcesPlaceholderPropertyValues = new HashMap<>(); propertySourcesPlaceholderPropertyValues.put("ignoreUnresolvablePlaceholders", true); registerBeanDefinition( registry, PropertySourcesPlaceholderConfigurer.class.getName(), PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues); } } static boolean registerBeanDefinition( BeanDefinitionRegistry registry, String beanName, Class<?> beanClass, Map<String, Object> extraPropertyValues) { if (registry.containsBeanDefinition(beanName)) { return false; } BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(beanClass).getBeanDefinition(); if (extraPropertyValues != null) { for (Map.Entry<String, Object> entry : extraPropertyValues.entrySet()) { beanDefinition.getPropertyValues().add(entry.getKey(), entry.getValue()); } } registry.registerBeanDefinition(beanName, beanDefinition); return true; } static boolean checkBeanExists(ConfigurableListableBeanFactory beanFactory, Class<?> targetClass) { String[] beanNames = beanFactory.getBeanNamesForType(targetClass, true, false); return (beanNames != null && beanNames.length > 0); } static ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor( AbstractBeanFactory beanFactory) { for (BeanPostProcessor beanPostProcessor : beanFactory.getBeanPostProcessors()) { if (beanPostProcessor instanceof ReferenceAnnotationBeanPostProcessor) { return (ReferenceAnnotationBeanPostProcessor) beanPostProcessor; } } return null; } static ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor( ApplicationContext applicationContext) { return getReferenceAnnotationBeanPostProcessor( (AbstractBeanFactory) applicationContext.getAutowireCapableBeanFactory()); } static DubboSpringInitContext getInitializationContext(BeanFactory beanFactory) { String beanName = DubboSpringInitContext.class.getName(); if (beanFactory != null && beanFactory.containsBean(beanName)) { return beanFactory.getBean(beanName, DubboSpringInitContext.class); } return null; } static ApplicationModel getApplicationModel(BeanFactory beanFactory) { String beanName = ApplicationModel.class.getName(); if (beanFactory != null && beanFactory.containsBean(beanName)) { return beanFactory.getBean(beanName, ApplicationModel.class); } return null; } static ModuleModel getModuleModel(BeanFactory beanFactory) { String beanName = ModuleModel.class.getName(); if (beanFactory != null && beanFactory.containsBean(beanName)) { return beanFactory.getBean(beanName, ModuleModel.class); } return null; } static ConfigManager getConfigManager(BeanFactory beanFactory) { String beanName = ConfigManager.BEAN_NAME; if (beanFactory.containsBean(beanName)) { return beanFactory.getBean(beanName, ConfigManager.class); } return null; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboAnnotationUtils.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboAnnotationUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.rpc.service.GenericService; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.springframework.util.Assert; import static org.springframework.util.ClassUtils.getAllInterfacesForClass; import static org.springframework.util.StringUtils.hasText; /** * Dubbo Annotation Utilities Class * * @see org.springframework.core.annotation.AnnotationUtils * @since 2.5.11 */ public class DubboAnnotationUtils { @Deprecated public static String resolveInterfaceName(Service service, Class<?> defaultInterfaceClass) throws IllegalStateException { String interfaceName; if (hasText(service.interfaceName())) { interfaceName = service.interfaceName(); } else if (!void.class.equals(service.interfaceClass())) { interfaceName = service.interfaceClass().getName(); } else if (defaultInterfaceClass.isInterface()) { interfaceName = defaultInterfaceClass.getName(); } else { throw new IllegalStateException("The @Service undefined interfaceClass or interfaceName, and the type " + defaultInterfaceClass.getName() + " is not a interface."); } return interfaceName; } /** * Resolve the service interface name from @Service annotation attributes. * <p/> * Note: the service interface class maybe not found locally if is a generic service. * * @param attributes annotation attributes of {@link Service @Service} * @param defaultInterfaceClass the default class of interface * @return the interface name if found * @throws IllegalStateException if interface name was not found */ public static String resolveInterfaceName(Map<String, Object> attributes, Class<?> defaultInterfaceClass) { // 1. get from DubboService.interfaceName() String interfaceClassName = AnnotationUtils.getAttribute(attributes, "interfaceName"); if (StringUtils.hasText(interfaceClassName)) { if ("org.apache.dubbo.rpc.service.GenericService".equals(interfaceClassName) || "com.alibaba.dubbo.rpc.service.GenericService".equals(interfaceClassName)) { throw new IllegalStateException( "@Service interfaceName() cannot be GenericService: " + interfaceClassName); } return interfaceClassName; } // 2. get from DubboService.interfaceClass() Class<?> interfaceClass = AnnotationUtils.getAttribute(attributes, "interfaceClass"); if (interfaceClass == null || void.class.equals(interfaceClass)) { // default or set void.class for purpose. interfaceClass = null; } else if (GenericService.class.isAssignableFrom(interfaceClass)) { throw new IllegalStateException( "@Service interfaceClass() cannot be GenericService :" + interfaceClass.getName()); } // 3. get from annotation element type, ignore GenericService if (interfaceClass == null && defaultInterfaceClass != null && !GenericService.class.isAssignableFrom(defaultInterfaceClass)) { // Find all interfaces from the annotated class // To resolve an issue : https://github.com/apache/dubbo/issues/3251 Class<?>[] allInterfaces = getAllInterfacesForClass(defaultInterfaceClass); if (allInterfaces.length > 0) { interfaceClass = allInterfaces[0]; } else { interfaceClass = defaultInterfaceClass; } } Assert.notNull( interfaceClass, "@Service interfaceClass() or interfaceName() or interface class must be present!"); // Assert.isTrue(interfaceClass.isInterface(), "The annotated type must be an interface!"); return interfaceClass.getName(); } @Deprecated public static String resolveInterfaceName(Reference reference, Class<?> defaultInterfaceClass) throws IllegalStateException { String interfaceName; if (!"".equals(reference.interfaceName())) { interfaceName = reference.interfaceName(); } else if (!void.class.equals(reference.interfaceClass())) { interfaceName = reference.interfaceClass().getName(); } else if (defaultInterfaceClass.isInterface()) { interfaceName = defaultInterfaceClass.getName(); } else { throw new IllegalStateException("The @Reference undefined interfaceClass or interfaceName, and the type " + defaultInterfaceClass.getName() + " is not a interface."); } return interfaceName; } /** * Resolve the parameters of {@link org.apache.dubbo.config.annotation.DubboService} * and {@link org.apache.dubbo.config.annotation.DubboReference} from the specified. * It iterates elements in order.The former element plays as key or key&value role, it would be * spilt if it contains specific string, for instance, ":" and "=". As for later element can't * be split in anytime.It will throw IllegalArgumentException If converted array length isn't * even number. * The convert cases below work in right way,which are best practice. * <pre> * (array->map) * ["a","b"] ==> {a=b} * [" a "," b "] ==> {a=b} * ["a=b"] ==>{a=b} * ["a:b"] ==>{a=b} * ["a=b","c","d"] ==>{a=b,c=d} * ["a","a:b"] ==>{a="a:b"} * ["a","a,b"] ==>{a="a,b"} * </pre> * * @param parameters * @return */ public static Map<String, String> convertParameters(String[] parameters) { if (ArrayUtils.isEmpty(parameters)) { return new HashMap<>(); } List<String> compatibleParameterArray = Arrays.stream(parameters) .map(String::trim) .reduce( new ArrayList<>(parameters.length), (list, parameter) -> { if (list.size() % 2 == 1) { // value doesn't split list.add(parameter); return list; } String[] sp1 = parameter.split(":"); if (sp1.length > 0 && sp1.length % 2 == 0) { // key split list.addAll(Arrays.stream(sp1).map(String::trim).collect(Collectors.toList())); return list; } sp1 = parameter.split("="); if (sp1.length > 0 && sp1.length % 2 == 0) { list.addAll(Arrays.stream(sp1).map(String::trim).collect(Collectors.toList())); return list; } list.add(parameter); return list; }, (a, b) -> a); return CollectionUtils.toStringMap(compatibleParameterArray.toArray(new String[0])); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/PropertySourcesUtils.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/PropertySourcesUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertyResolver; import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySources; import org.springframework.core.env.PropertySourcesPropertyResolver; import static java.util.Collections.unmodifiableMap; /** * {@link PropertySources} Utilities * * @see PropertySources */ public abstract class PropertySourcesUtils { /** * Get Sub {@link Properties} * * @param propertySources {@link PropertySource} Iterable * @param prefix the prefix of property name * @return Map * @see Properties */ public static Map<String, Object> getSubProperties(Iterable<PropertySource<?>> propertySources, String prefix) { MutablePropertySources mutablePropertySources = new MutablePropertySources(); for (PropertySource<?> source : propertySources) { mutablePropertySources.addLast(source); } return getSubProperties(mutablePropertySources, prefix); } /** * Get Sub {@link Properties} * * @param environment {@link ConfigurableEnvironment} * @param prefix the prefix of property name * @return Map * @see Properties */ public static Map<String, Object> getSubProperties(ConfigurableEnvironment environment, String prefix) { return getSubProperties(environment.getPropertySources(), environment, prefix); } /** * Normalize the prefix * * @param prefix the prefix * @return the prefix */ public static String normalizePrefix(String prefix) { return prefix.endsWith(".") ? prefix : prefix + "."; } /** * Get prefixed {@link Properties} * * @param propertySources {@link PropertySources} * @param prefix the prefix of property name * @return Map * @see Properties */ public static Map<String, Object> getSubProperties(PropertySources propertySources, String prefix) { return getSubProperties(propertySources, new PropertySourcesPropertyResolver(propertySources), prefix); } /** * Get prefixed {@link Properties} * * @param propertySources {@link PropertySources} * @param propertyResolver {@link PropertyResolver} to resolve the placeholder if present * @param prefix the prefix of property name * @return Map * @see Properties */ public static Map<String, Object> getSubProperties( PropertySources propertySources, PropertyResolver propertyResolver, String prefix) { Map<String, Object> subProperties = new LinkedHashMap<>(); String normalizedPrefix = normalizePrefix(prefix); Iterator<PropertySource<?>> iterator = propertySources.iterator(); while (iterator.hasNext()) { PropertySource<?> source = iterator.next(); for (String name : getPropertyNames(source)) { if (!subProperties.containsKey(name) && name.startsWith(normalizedPrefix)) { String subName = name.substring(normalizedPrefix.length()); if (!subProperties.containsKey(subName)) { // take first one Object value = source.getProperty(name); if (value instanceof String) { // Resolve placeholder value = propertyResolver.resolvePlaceholders((String) value); } subProperties.put(subName, value); } } } } return unmodifiableMap(subProperties); } /** * Get the property names as the array from the specified {@link PropertySource} instance. * * @param propertySource {@link PropertySource} instance * @return non-null */ public static String[] getPropertyNames(PropertySource propertySource) { String[] propertyNames = propertySource instanceof EnumerablePropertySource ? ((EnumerablePropertySource) propertySource).getPropertyNames() : null; if (propertyNames == null) { propertyNames = ObjectUtils.EMPTY_STRING_ARRAY; } return propertyNames; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/SpringCompatUtils.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/SpringCompatUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor; import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor; import org.apache.dubbo.config.spring.context.DubboInfraBeanRegisterPostProcessor; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.TypedStringValue; import org.springframework.core.type.MethodMetadata; import org.springframework.core.type.StandardMethodMetadata; /** * Spring Compatibility Utils for spring 3.x/4.x/5.x/6.x */ public class SpringCompatUtils { private static volatile Boolean factoryMethodMetadataEnabled = null; private static final Log logger = LogFactory.getLog(SpringCompatUtils.class); public static <T> T getPropertyValue(PropertyValues pvs, String propertyName) { PropertyValue pv = pvs.getPropertyValue(propertyName); Object val = pv != null ? pv.getValue() : null; if (val instanceof TypedStringValue) { TypedStringValue typedString = (TypedStringValue) val; return (T) typedString.getValue(); } return (T) val; } public static boolean isFactoryMethodMetadataEnabled() { if (factoryMethodMetadataEnabled == null) { try { // check AnnotatedBeanDefinition.getFactoryMethodMetadata() since spring 4.1 AnnotatedBeanDefinition.class.getMethod("getFactoryMethodMetadata"); // check MethodMetadata.getReturnTypeName() since spring 4.2 MethodMetadata.class.getMethod("getReturnTypeName"); factoryMethodMetadataEnabled = true; } catch (NoSuchMethodException e) { factoryMethodMetadataEnabled = false; } } return factoryMethodMetadataEnabled; } public static String getFactoryMethodReturnType(AnnotatedBeanDefinition annotatedBeanDefinition) { try { if (isFactoryMethodMetadataEnabled()) { MethodMetadata factoryMethodMetadata = annotatedBeanDefinition.getFactoryMethodMetadata(); return factoryMethodMetadata != null ? factoryMethodMetadata.getReturnTypeName() : null; } else { Object source = annotatedBeanDefinition.getSource(); if (source instanceof StandardMethodMetadata) { StandardMethodMetadata methodMetadata = (StandardMethodMetadata) source; Method introspectedMethod = methodMetadata.getIntrospectedMethod(); if (introspectedMethod != null) { return introspectedMethod.getReturnType().getName(); } } } } catch (Throwable e) { if (logger.isInfoEnabled()) { logger.info("get return type of AnnotatedBeanDefinition failed", e); } } return null; } public static MethodMetadata getFactoryMethodMetadata(AnnotatedBeanDefinition annotatedBeanDefinition) { if (isFactoryMethodMetadataEnabled()) { return annotatedBeanDefinition.getFactoryMethodMetadata(); } else { Object source = annotatedBeanDefinition.getSource(); if (source instanceof StandardMethodMetadata) { return (MethodMetadata) source; } return null; } } /** * Get the generic type of return type of the method. * * <pre> * Source method: * ReferenceBean&lt;DemoService> demoService() * * Result: DemoService.class * </pre> * * @param factoryMethodMetadata * @return */ public static Class getGenericTypeOfReturnType(MethodMetadata factoryMethodMetadata) { if (factoryMethodMetadata instanceof StandardMethodMetadata) { Method introspectedMethod = ((StandardMethodMetadata) factoryMethodMetadata).getIntrospectedMethod(); Type returnType = introspectedMethod.getGenericReturnType(); if (returnType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) returnType; Type actualTypeArgument = parameterizedType.getActualTypeArguments()[0]; if (actualTypeArgument instanceof Class) { return (Class) actualTypeArgument; } } } return null; } public static Class<?> referenceAnnotationBeanPostProcessor() { try { return Class.forName( "org.apache.dubbo.config.spring6.beans.factory.annotation.ReferenceAnnotationWithAotBeanPostProcessor"); } catch (ClassNotFoundException e) { return ReferenceAnnotationBeanPostProcessor.class; } } public static Class<?> serviceAnnotationPostProcessor() { try { return Class.forName( "org.apache.dubbo.config.spring6.beans.factory.annotation.ServiceAnnotationWithAotPostProcessor"); } catch (ClassNotFoundException e) { return ServiceAnnotationPostProcessor.class; } } public static Class<?> dubboInfraBeanRegisterPostProcessor() { try { return Class.forName("org.apache.dubbo.config.spring6.context.DubboInfraBeanRegisterPostProcessor"); } catch (ClassNotFoundException e) { return DubboInfraBeanRegisterPostProcessor.class; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotatedBeanDefinitionRegistryUtils.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotatedBeanDefinitionRegistryUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.SingletonBeanRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanNameGenerator; import org.springframework.context.annotation.AnnotatedBeanDefinitionReader; import org.springframework.context.annotation.AnnotationBeanNameGenerator; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.context.annotation.ConfigurationClassPostProcessor; import org.springframework.core.type.AnnotationMetadata; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; import static java.lang.String.format; import static java.util.Arrays.asList; import static org.apache.dubbo.common.utils.ReflectUtils.EMPTY_CLASS_ARRAY; import static org.springframework.context.annotation.AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR; import static org.springframework.util.ClassUtils.resolveClassName; import static org.springframework.util.ObjectUtils.nullSafeEquals; /** * Annotated {@link BeanDefinition} Utilities * * @see BeanDefinition */ public abstract class AnnotatedBeanDefinitionRegistryUtils { private static final Log logger = LogFactory.getLog(AnnotatedBeanDefinitionRegistryUtils.class); /** * Is present bean that was registered by the specified {@link Annotation annotated} {@link Class class} * * @param registry {@link BeanDefinitionRegistry} * @param annotatedClass the {@link Annotation annotated} {@link Class class} * @return if present, return <code>true</code>, or <code>false</code> * @since 1.0.3 */ public static boolean isPresentBean(BeanDefinitionRegistry registry, Class<?> annotatedClass) { boolean present = false; String[] beanNames = registry.getBeanDefinitionNames(); ClassLoader classLoader = annotatedClass.getClassLoader(); for (String beanName : beanNames) { BeanDefinition beanDefinition = registry.getBeanDefinition(beanName); if (beanDefinition instanceof AnnotatedBeanDefinition) { AnnotationMetadata annotationMetadata = ((AnnotatedBeanDefinition) beanDefinition).getMetadata(); String className = annotationMetadata.getClassName(); Class<?> targetClass = resolveClassName(className, classLoader); present = nullSafeEquals(targetClass, annotatedClass); if (present) { if (logger.isDebugEnabled()) { logger.debug(format( "The annotatedClass[class : %s , bean name : %s] was present in registry[%s]", className, beanName, registry)); } break; } } } return present; } /** * Register Beans if not present in {@link BeanDefinitionRegistry registry} * * @param registry {@link BeanDefinitionRegistry} * @param annotatedClasses {@link Annotation annotation} class */ public static void registerBeans(BeanDefinitionRegistry registry, Class<?>... annotatedClasses) { if (ObjectUtils.isEmpty(annotatedClasses)) { return; } Set<Class<?>> classesToRegister = new LinkedHashSet<Class<?>>(asList(annotatedClasses)); // Remove all annotated-classes that have been registered Iterator<Class<?>> iterator = classesToRegister.iterator(); while (iterator.hasNext()) { Class<?> annotatedClass = iterator.next(); if (isPresentBean(registry, annotatedClass)) { iterator.remove(); } } AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(registry); if (logger.isDebugEnabled()) { logger.debug(registry.getClass().getSimpleName() + " will register annotated classes : " + asList(annotatedClasses) + " ."); } reader.register(classesToRegister.toArray(EMPTY_CLASS_ARRAY)); } /** * Scan base packages for register {@link Component @Component}s * * @param registry {@link BeanDefinitionRegistry} * @param basePackages base packages * @return the count of registered components. */ public static int scanBasePackages(BeanDefinitionRegistry registry, String... basePackages) { int count = 0; if (!ObjectUtils.isEmpty(basePackages)) { boolean debugEnabled = logger.isDebugEnabled(); if (debugEnabled) { logger.debug(registry.getClass().getSimpleName() + " will scan base packages " + Arrays.asList(basePackages) + "."); } List<String> registeredBeanNames = Arrays.asList(registry.getBeanDefinitionNames()); ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(registry); count = classPathBeanDefinitionScanner.scan(basePackages); List<String> scannedBeanNames = new ArrayList<String>(count); scannedBeanNames.addAll(Arrays.asList(registry.getBeanDefinitionNames())); scannedBeanNames.removeAll(registeredBeanNames); if (debugEnabled) { logger.debug("The Scanned Components[ count : " + count + "] under base packages " + Arrays.asList(basePackages) + " : "); } for (String scannedBeanName : scannedBeanNames) { BeanDefinition scannedBeanDefinition = registry.getBeanDefinition(scannedBeanName); if (debugEnabled) { logger.debug("Component [ name : " + scannedBeanName + " , class : " + scannedBeanDefinition.getBeanClassName() + " ]"); } } } return count; } /** * It'd better to use BeanNameGenerator instance that should reference * {@link ConfigurationClassPostProcessor}, * thus it maybe a potential problem on bean name generation. * * @param registry {@link BeanDefinitionRegistry} * @return try to find the {@link BeanNameGenerator} bean named {@link AnnotationConfigUtils#CONFIGURATION_BEAN_NAME_GENERATOR}, * if it can't be found, return an instance of {@link AnnotationBeanNameGenerator} * @see SingletonBeanRegistry * @see AnnotationConfigUtils#CONFIGURATION_BEAN_NAME_GENERATOR * @see ConfigurationClassPostProcessor#processConfigBeanDefinitions * @since 1.0.6 */ public static BeanNameGenerator resolveAnnotatedBeanNameGenerator(BeanDefinitionRegistry registry) { BeanNameGenerator beanNameGenerator = null; if (registry instanceof SingletonBeanRegistry) { SingletonBeanRegistry singletonBeanRegistry = SingletonBeanRegistry.class.cast(registry); beanNameGenerator = (BeanNameGenerator) singletonBeanRegistry.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR); } if (beanNameGenerator == null) { if (logger.isInfoEnabled()) { logger.info("BeanNameGenerator bean can't be found in BeanFactory with name [" + CONFIGURATION_BEAN_NAME_GENERATOR + "]"); logger.info("BeanNameGenerator will be a instance of " + AnnotationBeanNameGenerator.class.getName() + " , it maybe a potential problem on bean name generation."); } beanNameGenerator = new AnnotationBeanNameGenerator(); } return beanNameGenerator; } /** * Finds a {@link Set} of {@link BeanDefinitionHolder BeanDefinitionHolders} * * @param scanner {@link ClassPathBeanDefinitionScanner} * @param packageToScan package to scan * @param registry {@link BeanDefinitionRegistry} * @param beanNameGenerator {@link BeanNameGenerator} * @return non-null */ public static Set<BeanDefinitionHolder> findBeanDefinitionHolders( ClassPathBeanDefinitionScanner scanner, String packageToScan, BeanDefinitionRegistry registry, BeanNameGenerator beanNameGenerator) { Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(packageToScan); Set<BeanDefinitionHolder> beanDefinitionHolders = new LinkedHashSet<BeanDefinitionHolder>(beanDefinitions.size()); for (BeanDefinition beanDefinition : beanDefinitions) { String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry); BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(beanDefinition, beanName); beanDefinitionHolders.add(beanDefinitionHolder); } return beanDefinitionHolders; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/EnvironmentUtils.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/EnvironmentUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.EnumerablePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.util.ObjectUtils; /** * The utilities class for {@link Environment} * * @see Environment * @since 2.7.0 */ public abstract class EnvironmentUtils { /** * The separator of property name */ public static final String PROPERTY_NAME_SEPARATOR = "."; /** * The prefix of property name of Dubbo */ public static final String DUBBO_PREFIX = "dubbo"; /** * Extras The properties from {@link ConfigurableEnvironment} * * @param environment {@link ConfigurableEnvironment} * @return Read-only Map */ public static Map<String, Object> extractProperties(ConfigurableEnvironment environment) { return Collections.unmodifiableMap(doExtraProperties(environment)); } private static Map<String, Object> doExtraProperties(ConfigurableEnvironment environment) { Map<String, Object> properties = new LinkedHashMap<>(); // orderly Map<String, PropertySource<?>> map = doGetPropertySources(environment); for (PropertySource<?> source : map.values()) { if (source instanceof EnumerablePropertySource) { EnumerablePropertySource propertySource = (EnumerablePropertySource) source; String[] propertyNames = propertySource.getPropertyNames(); if (ObjectUtils.isEmpty(propertyNames)) { continue; } for (String propertyName : propertyNames) { if (!properties.containsKey(propertyName)) { // put If absent properties.put(propertyName, propertySource.getProperty(propertyName)); } } } } return properties; } private static Map<String, PropertySource<?>> doGetPropertySources(ConfigurableEnvironment environment) { Map<String, PropertySource<?>> map = new LinkedHashMap<>(); MutablePropertySources sources = environment.getPropertySources(); for (PropertySource<?> source : sources) { extract("", map, source); } return map; } private static void extract(String root, Map<String, PropertySource<?>> map, PropertySource<?> source) { if (source instanceof CompositePropertySource) { for (PropertySource<?> nest : ((CompositePropertySource) source).getPropertySources()) { extract(source.getName() + ":", map, nest); } } else { map.put(root + source.getName(), source); } } /** * Filters Dubbo Properties from {@link ConfigurableEnvironment} * * @param environment {@link ConfigurableEnvironment} * @return Read-only SortedMap */ public static SortedMap<String, String> filterDubboProperties(ConfigurableEnvironment environment) { SortedMap<String, String> dubboProperties = new TreeMap<>(); Map<String, Object> properties = extractProperties(environment); for (Map.Entry<String, Object> entry : properties.entrySet()) { String propertyName = entry.getKey(); if (propertyName.startsWith(DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR) && entry.getValue() != null) { dubboProperties.put( propertyName, environment.resolvePlaceholders(entry.getValue().toString())); } } return Collections.unmodifiableSortedMap(dubboProperties); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotationUtils.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotationUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertyResolver; import org.springframework.util.ClassUtils; import static java.lang.String.valueOf; import static java.util.Arrays.asList; import static org.springframework.core.annotation.AnnotationAttributes.fromMap; import static org.springframework.core.annotation.AnnotationUtils.findAnnotation; import static org.springframework.core.annotation.AnnotationUtils.getDefaultValue; import static org.springframework.util.ClassUtils.resolveClassName; import static org.springframework.util.CollectionUtils.arrayToList; import static org.springframework.util.CollectionUtils.isEmpty; import static org.springframework.util.ObjectUtils.nullSafeEquals; import static org.springframework.util.ReflectionUtils.findMethod; import static org.springframework.util.ReflectionUtils.invokeMethod; import static org.springframework.util.StringUtils.trimWhitespace; /** * {@link Annotation} Utilities * @see Annotation */ @SuppressWarnings("unchecked") public abstract class AnnotationUtils { /** * The class name of AnnotatedElementUtils that is introduced since Spring Framework 4 */ public static final String ANNOTATED_ELEMENT_UTILS_CLASS_NAME = "org.springframework.core.annotation.AnnotatedElementUtils"; /** * Is specified {@link Annotation} present on {@link Method}'s declaring class or parameters or itself. * * @param method {@link Method} * @param annotationClass {@link Annotation} type * @param <A> {@link Annotation} type * @return If present , return <code>true</code> , or <code>false</code> */ public static <A extends Annotation> boolean isPresent(Method method, Class<A> annotationClass) { Map<ElementType, List<A>> annotationsMap = findAnnotations(method, annotationClass); return !annotationsMap.isEmpty(); } /** * Find specified {@link Annotation} type maps from {@link Method} * * @param method {@link Method} * @param annotationClass {@link Annotation} type * @param <A> {@link Annotation} type * @return {@link Annotation} type maps , the {@link ElementType} as key , * the list of {@link Annotation} as value. * If {@link Annotation} was annotated on {@link Method}'s parameters{@link ElementType#PARAMETER} , * the associated {@link Annotation} list may contain multiple elements. */ public static <A extends Annotation> Map<ElementType, List<A>> findAnnotations( Method method, Class<A> annotationClass) { Retention retention = annotationClass.getAnnotation(Retention.class); RetentionPolicy retentionPolicy = retention.value(); if (!RetentionPolicy.RUNTIME.equals(retentionPolicy)) { return Collections.emptyMap(); } Map<ElementType, List<A>> annotationsMap = new LinkedHashMap<ElementType, List<A>>(); Target target = annotationClass.getAnnotation(Target.class); ElementType[] elementTypes = target.value(); for (ElementType elementType : elementTypes) { List<A> annotationsList = new LinkedList<A>(); switch (elementType) { case PARAMETER: Annotation[][] parameterAnnotations = method.getParameterAnnotations(); for (Annotation[] annotations : parameterAnnotations) { for (Annotation annotation : annotations) { if (annotationClass.equals(annotation.annotationType())) { annotationsList.add((A) annotation); } } } break; case METHOD: A annotation = findAnnotation(method, annotationClass); if (annotation != null) { annotationsList.add(annotation); } break; case TYPE: Class<?> beanType = method.getDeclaringClass(); A annotation2 = findAnnotation(beanType, annotationClass); if (annotation2 != null) { annotationsList.add(annotation2); } break; } if (!annotationsList.isEmpty()) { annotationsMap.put(elementType, annotationsList); } } return Collections.unmodifiableMap(annotationsMap); } /** * Get the {@link Annotation} attributes * * @param annotation specified {@link Annotation} * @param ignoreDefaultValue whether ignore default value or not * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return non-null * @since 1.0.2 */ public static Map<String, Object> getAttributes( Annotation annotation, boolean ignoreDefaultValue, String... ignoreAttributeNames) { return getAttributes(annotation, null, ignoreDefaultValue, ignoreAttributeNames); } /** * Get the {@link Annotation} attributes * * @param annotation specified {@link Annotation} * @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment} * @param ignoreDefaultValue whether ignore default value or not * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return non-null * @since 1.0.2 */ public static Map<String, Object> getAttributes( Annotation annotation, PropertyResolver propertyResolver, boolean ignoreDefaultValue, String... ignoreAttributeNames) { return getAttributes(annotation, propertyResolver, false, false, ignoreDefaultValue, ignoreAttributeNames); } /** * Get the {@link Annotation} attributes * * @param annotationAttributes the attributes of specified {@link Annotation} * @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment} * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return non-null * @since 1.0.4 */ public static Map<String, Object> getAttributes( Map<String, Object> annotationAttributes, PropertyResolver propertyResolver, String... ignoreAttributeNames) { Set<String> ignoreAttributeNamesSet = new HashSet<String>((Collection<? extends String>) arrayToList(ignoreAttributeNames)); Map<String, Object> actualAttributes = new LinkedHashMap<String, Object>(); for (Map.Entry<String, Object> annotationAttribute : annotationAttributes.entrySet()) { String attributeName = annotationAttribute.getKey(); Object attributeValue = annotationAttribute.getValue(); // ignore attribute name if (ignoreAttributeNamesSet.contains(attributeName)) { continue; } if (attributeValue instanceof String) { attributeValue = resolvePlaceholders(valueOf(attributeValue), propertyResolver); } else if (attributeValue instanceof String[]) { String[] values = (String[]) attributeValue; for (int i = 0; i < values.length; i++) { values[i] = resolvePlaceholders(values[i], propertyResolver); } attributeValue = values; } actualAttributes.put(attributeName, attributeValue); } return actualAttributes; } /** * @param annotation specified {@link Annotation} * @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment} * @param classValuesAsString whether to turn Class references into Strings (for * compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to * preserve them as Class references * @param nestedAnnotationsAsMap whether to turn nested Annotation instances into * {@link AnnotationAttributes} maps (for compatibility with * {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as * Annotation instances * @param ignoreDefaultValue whether ignore default value or not * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return * @since 1.0.11 */ public static Map<String, Object> getAttributes( Annotation annotation, PropertyResolver propertyResolver, boolean classValuesAsString, boolean nestedAnnotationsAsMap, boolean ignoreDefaultValue, String... ignoreAttributeNames) { Map<String, Object> annotationAttributes = org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes( annotation, classValuesAsString, nestedAnnotationsAsMap); String[] actualIgnoreAttributeNames = ignoreAttributeNames; if (ignoreDefaultValue && !isEmpty(annotationAttributes)) { List<String> attributeNamesToIgnore = new LinkedList<String>(asList(ignoreAttributeNames)); for (Map.Entry<String, Object> annotationAttribute : annotationAttributes.entrySet()) { String attributeName = annotationAttribute.getKey(); Object attributeValue = annotationAttribute.getValue(); if (nullSafeEquals(attributeValue, getDefaultValue(annotation, attributeName))) { attributeNamesToIgnore.add(attributeName); } } // extends the ignored list actualIgnoreAttributeNames = attributeNamesToIgnore.toArray(new String[attributeNamesToIgnore.size()]); } return getAttributes(annotationAttributes, propertyResolver, actualIgnoreAttributeNames); } private static String resolvePlaceholders(String attributeValue, PropertyResolver propertyResolver) { String resolvedValue = attributeValue; if (propertyResolver != null) { resolvedValue = propertyResolver.resolvePlaceholders(resolvedValue); resolvedValue = trimWhitespace(resolvedValue); } return resolvedValue; } /** * Get the attribute value * * @param annotation {@link Annotation annotation} * @param attributeName the name of attribute * @param <T> the type of attribute value * @return the attribute value if found * @since 1.0.3 */ public static <T> T getAttribute(Annotation annotation, String attributeName) { return getAttribute( org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes(annotation), attributeName); } /** * Get the attribute value * * @param attributes {@link Map the annotation attributes} or {@link AnnotationAttributes} * @param attributeName the name of attribute * @param <T> the type of attribute value * @return the attribute value if found * @since 1.0.3 */ public static <T> T getAttribute(Map<String, Object> attributes, String attributeName) { return getAttribute(attributes, attributeName, false); } /** * Get the attribute value the will * * @param attributes {@link Map the annotation attributes} or {@link AnnotationAttributes} * @param attributeName the name of attribute * @param required the required attribute or not * @param <T> the type of attribute value * @return the attribute value if found * @throws IllegalStateException if attribute value can't be found * @since 1.0.6 */ public static <T> T getAttribute(Map<String, Object> attributes, String attributeName, boolean required) { T value = getAttribute(attributes, attributeName, null); if (required && value == null) { throw new IllegalStateException("The attribute['" + attributeName + "] is required!"); } return value; } /** * Get the attribute value with default value * * @param attributes {@link Map the annotation attributes} or {@link AnnotationAttributes} * @param attributeName the name of attribute * @param defaultValue the default value of attribute * @param <T> the type of attribute value * @return the attribute value if found * @since 1.0.6 */ public static <T> T getAttribute(Map<String, Object> attributes, String attributeName, T defaultValue) { T value = (T) attributes.get(attributeName); return value == null ? defaultValue : value; } /** * Get the required attribute value * * @param attributes {@link Map the annotation attributes} or {@link AnnotationAttributes} * @param attributeName the name of attribute * @param <T> the type of attribute value * @return the attribute value if found * @throws IllegalStateException if attribute value can't be found * @since 1.0.6 */ public static <T> T getRequiredAttribute(Map<String, Object> attributes, String attributeName) { return getAttribute(attributes, attributeName, true); } /** * Get the {@link AnnotationAttributes} * * @param annotation specified {@link Annotation} * @param ignoreDefaultValue whether ignore default value or not * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return non-null * @see #getAnnotationAttributes(Annotation, PropertyResolver, boolean, String...) * @since 1.0.3 */ public static AnnotationAttributes getAnnotationAttributes( Annotation annotation, boolean ignoreDefaultValue, String... ignoreAttributeNames) { return getAnnotationAttributes(annotation, null, ignoreDefaultValue, ignoreAttributeNames); } /** * Get the {@link AnnotationAttributes} * * @param annotation specified {@link Annotation} * @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment} * @param classValuesAsString whether to turn Class references into Strings (for * compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to * preserve them as Class references * @param nestedAnnotationsAsMap whether to turn nested Annotation instances into * {@link AnnotationAttributes} maps (for compatibility with * {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as * Annotation instances * @param ignoreAttributeNames the attribute names of annotation should be ignored * @param ignoreDefaultValue whether ignore default value or not * @return non-null * @see #getAttributes(Annotation, PropertyResolver, boolean, String...) * @see #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...) * @since 1.0.11 */ public static AnnotationAttributes getAnnotationAttributes( Annotation annotation, PropertyResolver propertyResolver, boolean classValuesAsString, boolean nestedAnnotationsAsMap, boolean ignoreDefaultValue, String... ignoreAttributeNames) { return fromMap(getAttributes( annotation, propertyResolver, classValuesAsString, nestedAnnotationsAsMap, ignoreDefaultValue, ignoreAttributeNames)); } /** * Get the {@link AnnotationAttributes} * * @param annotation specified {@link Annotation} * @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment} * @param ignoreDefaultValue whether ignore default value or not * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return non-null * @see #getAttributes(Annotation, PropertyResolver, boolean, String...) * @see #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...) * @since 1.0.3 */ public static AnnotationAttributes getAnnotationAttributes( Annotation annotation, PropertyResolver propertyResolver, boolean ignoreDefaultValue, String... ignoreAttributeNames) { return getAnnotationAttributes( annotation, propertyResolver, false, false, ignoreDefaultValue, ignoreAttributeNames); } /** * Get the {@link AnnotationAttributes} * * @param annotatedElement {@link AnnotatedElement the annotated element} * @param annotationType the {@link Class tyoe} pf {@link Annotation annotation} * @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment} * @param ignoreDefaultValue whether ignore default value or not * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return if <code>annotatedElement</code> can't be found in <code>annotatedElement</code>, return <code>null</code> * @since 1.0.3 */ public static AnnotationAttributes getAnnotationAttributes( AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType, PropertyResolver propertyResolver, boolean ignoreDefaultValue, String... ignoreAttributeNames) { return getAnnotationAttributes( annotatedElement, annotationType, propertyResolver, false, false, ignoreDefaultValue, ignoreAttributeNames); } /** * Get the {@link AnnotationAttributes} * * @param annotatedElement {@link AnnotatedElement the annotated element} * @param annotationType the {@link Class tyoe} pf {@link Annotation annotation} * @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment} * @param ignoreDefaultValue whether ignore default value or not * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return if <code>annotatedElement</code> can't be found in <code>annotatedElement</code>, return <code>null</code> * @since 1.0.11 */ public static AnnotationAttributes getAnnotationAttributes( AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType, PropertyResolver propertyResolver, boolean classValuesAsString, boolean nestedAnnotationsAsMap, boolean ignoreDefaultValue, String... ignoreAttributeNames) { Annotation annotation = annotatedElement.getAnnotation(annotationType); return annotation == null ? null : getAnnotationAttributes( annotation, propertyResolver, classValuesAsString, nestedAnnotationsAsMap, ignoreDefaultValue, ignoreAttributeNames); } /** * Get the {@link AnnotationAttributes}, if the argument <code>tryMergedAnnotation</code> is <code>true</code>, * the {@link AnnotationAttributes} will be got from * {@link #tryGetMergedAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...) merged annotation} first, * if failed, and then to get from * {@link #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, boolean, String...) normal one} * * @param annotatedElement {@link AnnotatedElement the annotated element} * @param annotationType the {@link Class tyoe} pf {@link Annotation annotation} * @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment} * @param ignoreDefaultValue whether ignore default value or not * @param tryMergedAnnotation whether try merged annotation or not * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return if <code>annotatedElement</code> can't be found in <code>annotatedElement</code>, return <code>null</code> * @since 1.0.3 */ public static AnnotationAttributes getAnnotationAttributes( AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType, PropertyResolver propertyResolver, boolean ignoreDefaultValue, boolean tryMergedAnnotation, String... ignoreAttributeNames) { return getAnnotationAttributes( annotatedElement, annotationType, propertyResolver, false, false, ignoreDefaultValue, tryMergedAnnotation, ignoreAttributeNames); } /** * Get the {@link AnnotationAttributes}, if the argument <code>tryMergedAnnotation</code> is <code>true</code>, * the {@link AnnotationAttributes} will be got from * {@link #tryGetMergedAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...) merged annotation} first, * if failed, and then to get from * {@link #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, boolean, String...) normal one} * * @param annotatedElement {@link AnnotatedElement the annotated element} * @param annotationType the {@link Class tyoe} pf {@link Annotation annotation} * @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment} * @param classValuesAsString whether to turn Class references into Strings (for * compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to * preserve them as Class references * @param nestedAnnotationsAsMap whether to turn nested Annotation instances into * {@link AnnotationAttributes} maps (for compatibility with * {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as * Annotation instances * @param ignoreDefaultValue whether ignore default value or not * @param tryMergedAnnotation whether try merged annotation or not * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return if <code>annotatedElement</code> can't be found in <code>annotatedElement</code>, return <code>null</code> * @since 1.0.11 */ public static AnnotationAttributes getAnnotationAttributes( AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType, PropertyResolver propertyResolver, boolean classValuesAsString, boolean nestedAnnotationsAsMap, boolean ignoreDefaultValue, boolean tryMergedAnnotation, String... ignoreAttributeNames) { AnnotationAttributes attributes = null; if (tryMergedAnnotation) { attributes = tryGetMergedAnnotationAttributes( annotatedElement, annotationType, propertyResolver, classValuesAsString, nestedAnnotationsAsMap, ignoreDefaultValue, ignoreAttributeNames); } if (attributes == null) { attributes = getAnnotationAttributes( annotatedElement, annotationType, propertyResolver, classValuesAsString, nestedAnnotationsAsMap, ignoreDefaultValue, ignoreAttributeNames); } return attributes; } /** * Try to get the merged {@link Annotation annotation} * * @param annotatedElement {@link AnnotatedElement the annotated element} * @param annotationType the {@link Class tyoe} pf {@link Annotation annotation} * @return If current version of Spring Framework is below 4.2, return <code>null</code> * @since 1.0.3 */ public static Annotation tryGetMergedAnnotation( AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType) { return tryGetMergedAnnotation(annotatedElement, annotationType, false, false); } /** * Try to get the merged {@link Annotation annotation} * * @param annotatedElement {@link AnnotatedElement the annotated element} * @param annotationType the {@link Class tyoe} pf {@link Annotation annotation} * @param classValuesAsString whether to turn Class references into Strings (for * compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to * preserve them as Class references * @param nestedAnnotationsAsMap whether to turn nested Annotation instances into * {@link AnnotationAttributes} maps (for compatibility with * {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as * Annotation instances * @return If current version of Spring Framework is below 4.2, return <code>null</code> * @since 1.0.11 */ public static Annotation tryGetMergedAnnotation( AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType, boolean classValuesAsString, boolean nestedAnnotationsAsMap) { Annotation mergedAnnotation = null; ClassLoader classLoader = annotationType.getClassLoader(); if (ClassUtils.isPresent(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, classLoader)) { Class<?> annotatedElementUtilsClass = resolveClassName(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, classLoader); // getMergedAnnotation method appears in the Spring Framework 5.x Method getMergedAnnotationMethod = findMethod(annotatedElementUtilsClass, "getMergedAnnotation", AnnotatedElement.class, Class.class); if (getMergedAnnotationMethod != null) { mergedAnnotation = (Annotation) invokeMethod(getMergedAnnotationMethod, null, annotatedElement, annotationType); } else { // getMergedAnnotation method appears in the Spring Framework 4.2 getMergedAnnotationMethod = findMethod( annotatedElementUtilsClass, "getMergedAnnotation", AnnotatedElement.class, Class.class, boolean.class, boolean.class); if (getMergedAnnotationMethod != null) { mergedAnnotation = (Annotation) invokeMethod( getMergedAnnotationMethod, null, annotatedElement, annotationType, classValuesAsString, nestedAnnotationsAsMap); } } } return mergedAnnotation; } /** * Try to get {@link AnnotationAttributes the annotation attributes} after merging and resolving the placeholders * * @param annotatedElement {@link AnnotatedElement the annotated element} * @param annotationType the {@link Class tyoe} pf {@link Annotation annotation} * @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment} * @param ignoreDefaultValue whether ignore default value or not * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return If the specified annotation type is not found, return <code>null</code> * @since 1.0.3 */ public static AnnotationAttributes tryGetMergedAnnotationAttributes( AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType, PropertyResolver propertyResolver, boolean ignoreDefaultValue, String... ignoreAttributeNames) { return tryGetMergedAnnotationAttributes( annotatedElement, annotationType, propertyResolver, false, false, ignoreDefaultValue, ignoreAttributeNames); } /** * Try to get {@link AnnotationAttributes the annotation attributes} after merging and resolving the placeholders * * @param annotatedElement {@link AnnotatedElement the annotated element} * @param annotationType the {@link Class tyoe} pf {@link Annotation annotation} * @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment} * @param classValuesAsString whether to turn Class references into Strings (for * compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to * preserve them as Class references * @param nestedAnnotationsAsMap whether to turn nested Annotation instances into * {@link AnnotationAttributes} maps (for compatibility with * {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as * Annotation instances * @param ignoreDefaultValue whether ignore default value or not * @param ignoreAttributeNames the attribute names of annotation should be ignored * @return If the specified annotation type is not found, return <code>null</code> * @since 1.0.11 */ public static AnnotationAttributes tryGetMergedAnnotationAttributes( AnnotatedElement annotatedElement, Class<? extends Annotation> annotationType, PropertyResolver propertyResolver, boolean classValuesAsString, boolean nestedAnnotationsAsMap, boolean ignoreDefaultValue, String... ignoreAttributeNames) { Annotation annotation = tryGetMergedAnnotation(annotatedElement, annotationType, classValuesAsString, nestedAnnotationsAsMap); return annotation == null ? null
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
true
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/GenericBeanPostProcessorAdapter.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/GenericBeanPostProcessorAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.util.ClassUtils; /** * Generic {@link BeanPostProcessor} Adapter * * @see BeanPostProcessor */ @SuppressWarnings("unchecked") public abstract class GenericBeanPostProcessorAdapter<T> implements BeanPostProcessor { private final Class<T> beanType; public GenericBeanPostProcessorAdapter() { ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); this.beanType = (Class<T>) actualTypeArguments[0]; } @Override public final Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (ClassUtils.isAssignableValue(beanType, bean)) { return doPostProcessBeforeInitialization((T) bean, beanName); } return bean; } @Override public final Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (ClassUtils.isAssignableValue(beanType, bean)) { return doPostProcessAfterInitialization((T) bean, beanName); } return bean; } /** * Bean Type * * @return Bean Type */ public final Class<T> getBeanType() { return beanType; } /** * Adapter BeanPostProcessor#postProcessBeforeInitialization(Object, String) method , sub-type * could override this method. * * @param bean Bean Object * @param beanName Bean Name * @return Bean Object * @see BeanPostProcessor#postProcessBeforeInitialization(Object, String) */ protected T doPostProcessBeforeInitialization(T bean, String beanName) throws BeansException { processBeforeInitialization(bean, beanName); return bean; } /** * Adapter BeanPostProcessor#postProcessAfterInitialization(Object, String) method , sub-type * could override this method. * * @param bean Bean Object * @param beanName Bean Name * @return Bean Object * @see BeanPostProcessor#postProcessAfterInitialization(Object, String) */ protected T doPostProcessAfterInitialization(T bean, String beanName) throws BeansException { processAfterInitialization(bean, beanName); return bean; } /** * Process {@link T Bean} with name without return value before initialization, * <p> * This method will be invoked by BeanPostProcessor#postProcessBeforeInitialization(Object, String) * * @param bean Bean Object * @param beanName Bean Name * @throws BeansException in case of errors */ protected void processBeforeInitialization(T bean, String beanName) throws BeansException {} /** * Process {@link T Bean} with name without return value after initialization, * <p> * This method will be invoked by BeanPostProcessor#postProcessAfterInitialization(Object, String) * * @param bean Bean Object * @param beanName Bean Name * @throws BeansException in case of errors */ protected void processAfterInitialization(T bean, String beanName) throws BeansException {} }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/WrapperUtils.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/WrapperUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.util.Assert; /** * The utilities class for wrapper interfaces * */ public abstract class WrapperUtils { /** * Unwrap {@link BeanFactory} to {@link ConfigurableListableBeanFactory} * * @param beanFactory {@link ConfigurableListableBeanFactory} * @return {@link ConfigurableListableBeanFactory} * @throws IllegalArgumentException If <code>beanFactory</code> argument is not an instance of {@link ConfigurableListableBeanFactory} */ public static ConfigurableListableBeanFactory unwrap(BeanFactory beanFactory) throws IllegalArgumentException { Assert.isInstanceOf( ConfigurableListableBeanFactory.class, beanFactory, "The 'beanFactory' argument is not an instance of ConfigurableListableBeanFactory, " + "is it running in Spring container?"); return ConfigurableListableBeanFactory.class.cast(beanFactory); } /** * Unwrap {@link Environment} to {@link ConfigurableEnvironment} * * @param environment {@link Environment} * @return {@link ConfigurableEnvironment} * @throws IllegalArgumentException If <code>environment</code> argument is not an instance of {@link ConfigurableEnvironment} */ public static ConfigurableEnvironment unwrap(Environment environment) throws IllegalArgumentException { Assert.isInstanceOf( ConfigurableEnvironment.class, environment, "The 'environment' argument is not a instance of ConfigurableEnvironment, " + "is it running in Spring container?"); return (ConfigurableEnvironment) environment; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LazyTargetInvocationHandler.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LazyTargetInvocationHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class LazyTargetInvocationHandler implements InvocationHandler { private final LazyTargetSource lazyTargetSource; private volatile Object target; public LazyTargetInvocationHandler(LazyTargetSource lazyTargetSource) { this.lazyTargetSource = lazyTargetSource; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 0) { if ("toString".equals(methodName)) { if (target != null) { return target.toString(); } else { return this.toString(); } } else if ("hashCode".equals(methodName)) { return this.hashCode(); } } else if (parameterTypes.length == 1 && "equals".equals(methodName)) { return this.equals(args[0]); } if (target == null) { target = lazyTargetSource.getTarget(); } if (method.getDeclaringClass().isInstance(target)) { try { return method.invoke(target, args); } catch (InvocationTargetException exception) { Throwable targetException = exception.getTargetException(); if (targetException != null) { throw targetException; } } } throw new IllegalStateException("The proxied interface [" + method.getDeclaringClass() + "] contains a method [" + method + "] that is not implemented by the proxy class [" + target.getClass() + "]"); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/SpringParameterNameReader.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/SpringParameterNameReader.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.util; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.utils.ParameterNameReader; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.springframework.core.DefaultParameterNameDiscoverer; import org.springframework.core.ParameterNameDiscoverer; @Activate(onClass = "org.springframework.core.DefaultParameterNameDiscoverer") public class SpringParameterNameReader implements ParameterNameReader { private final ParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer(); @Override public String[] readParameterNames(Method method) { return discoverer.getParameterNames(method); } @Override public String[] readParameterNames(Constructor<?> ctor) { return discoverer.getParameterNames(ctor); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServicePackagesHolder.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServicePackagesHolder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.beans.factory.annotation; import java.util.HashSet; import java.util.Set; /** * A temp holder for scanned packages of service. */ public class ServicePackagesHolder { public static final String BEAN_NAME = "dubboServicePackagesHolder"; private final Set<String> scannedPackages = new HashSet<>(); private final Set<String> scannedClasses = new HashSet<>(); public void addScannedPackage(String apackage) { apackage = normalizePackage(apackage); synchronized (scannedPackages) { scannedPackages.add(apackage); } } public boolean isPackageScanned(String packageName) { packageName = normalizePackage(packageName); synchronized (scannedPackages) { if (scannedPackages.contains(packageName)) { return true; } for (String scannedPackage : scannedPackages) { if (isSubPackage(packageName, scannedPackage)) { return true; } } } return false; } public void addScannedClass(String className) { synchronized (scannedClasses) { scannedClasses.add(className); } } public boolean isClassScanned(String className) { synchronized (scannedClasses) { return scannedClasses.contains(className); } } /** * Whether test package is sub package of parent package * @param testPkg * @param parent * @return */ private boolean isSubPackage(String testPkg, String parent) { // child pkg startsWith parent pkg return testPkg.startsWith(parent); } private String normalizePackage(String apackage) { if (!apackage.endsWith(".")) { apackage += "."; } return apackage; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.beans.factory.annotation; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.util.AnnotationUtils; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; import static org.apache.dubbo.config.spring.util.DubboAnnotationUtils.resolveInterfaceName; import static org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes; /** * Dubbo {@link Service @Service} Bean Builder * * @see Service * @see Reference * @see ServiceBean * @see ReferenceBean * @since 2.6.5 */ public class ServiceBeanNameBuilder { private static final String SEPARATOR = ":"; // Required private final String interfaceClassName; private final Environment environment; // Optional private String version; private String group; private ServiceBeanNameBuilder(Class<?> interfaceClass, Environment environment) { this(interfaceClass.getName(), environment); } private ServiceBeanNameBuilder(String interfaceClassName, Environment environment) { this.interfaceClassName = interfaceClassName; this.environment = environment; } private ServiceBeanNameBuilder( AnnotationAttributes attributes, Class<?> defaultInterfaceClass, Environment environment) { this(resolveInterfaceName(attributes, defaultInterfaceClass), environment); this.group(AnnotationUtils.getAttribute(attributes, "group")); this.version(AnnotationUtils.getAttribute(attributes, "version")); } /** * @param attributes * @param defaultInterfaceClass * @param environment * @return * @since 2.7.3 */ public static ServiceBeanNameBuilder create( AnnotationAttributes attributes, Class<?> defaultInterfaceClass, Environment environment) { return new ServiceBeanNameBuilder(attributes, defaultInterfaceClass, environment); } public static ServiceBeanNameBuilder create(Class<?> interfaceClass, Environment environment) { return new ServiceBeanNameBuilder(interfaceClass, environment); } public static ServiceBeanNameBuilder create(String interfaceClass, Environment environment) { return new ServiceBeanNameBuilder(interfaceClass, environment); } public static ServiceBeanNameBuilder create(Service service, Class<?> interfaceClass, Environment environment) { return create(getAnnotationAttributes(service, false, false), interfaceClass, environment); } public static ServiceBeanNameBuilder create(Reference reference, Class<?> interfaceClass, Environment environment) { return create(getAnnotationAttributes(reference, false, false), interfaceClass, environment); } private static void append(StringBuilder builder, String value) { builder.append(SEPARATOR); if (StringUtils.hasText(value)) { builder.append(value); } } public ServiceBeanNameBuilder group(String group) { this.group = group; return this; } public ServiceBeanNameBuilder version(String version) { this.version = version; return this; } public String build() { StringBuilder beanNameBuilder = new StringBuilder("ServiceBean"); // Required append(beanNameBuilder, interfaceClassName); // Optional append(beanNameBuilder, version); append(beanNameBuilder, group); // Build and remove last ":" String rawBeanName = beanNameBuilder.toString(); // Resolve placeholders return environment.resolvePlaceholders(rawBeanName); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapter.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AnnotationPropertyValuesAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.beans.factory.annotation; import org.apache.dubbo.config.spring.util.AnnotationUtils; import java.lang.annotation.Annotation; import java.util.Map; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyValues; import org.springframework.core.env.PropertyResolver; /** * {@link Annotation} {@link PropertyValues} Adapter * * @see Annotation * @see PropertyValues * @since 2.5.11 */ public class AnnotationPropertyValuesAdapter implements PropertyValues { private final PropertyValues delegate; /** * @param attributes * @param propertyResolver * @param ignoreAttributeNames * @since 2.7.3 */ public AnnotationPropertyValuesAdapter( Map<String, Object> attributes, PropertyResolver propertyResolver, String... ignoreAttributeNames) { this.delegate = new MutablePropertyValues( AnnotationUtils.getAttributes(attributes, propertyResolver, ignoreAttributeNames)); } public AnnotationPropertyValuesAdapter( Annotation annotation, PropertyResolver propertyResolver, boolean ignoreDefaultValue, String... ignoreAttributeNames) { this.delegate = new MutablePropertyValues( AnnotationUtils.getAttributes(annotation, propertyResolver, ignoreDefaultValue, ignoreAttributeNames)); } public AnnotationPropertyValuesAdapter( Annotation annotation, PropertyResolver propertyResolver, String... ignoreAttributeNames) { this(annotation, propertyResolver, true, ignoreAttributeNames); } @Override public PropertyValue[] getPropertyValues() { return delegate.getPropertyValues(); } @Override public PropertyValue getPropertyValue(String propertyName) { return delegate.getPropertyValue(propertyName); } @Override public PropertyValues changesSince(PropertyValues old) { return delegate.changesSince(old); } @Override public boolean contains(String propertyName) { return delegate.contains(propertyName); } @Override public boolean isEmpty() { return delegate.isEmpty(); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.beans.factory.annotation; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.config.spring.util.AnnotationUtils; import java.beans.PropertyDescriptor; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.annotation.InjectionMetadata; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.core.Ordered; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.env.Environment; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; import static org.springframework.core.BridgeMethodResolver.findBridgedMethod; import static org.springframework.core.BridgeMethodResolver.isVisibilityBridgeMethodPair; /** * Abstract common {@link BeanPostProcessor} implementation for customized annotation that annotated injected-object. */ @SuppressWarnings("unchecked") public abstract class AbstractAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor, BeanFactoryAware, BeanClassLoaderAware, EnvironmentAware, DisposableBean { private static final int CACHE_SIZE = Integer.getInteger("", 32); private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final Class<? extends Annotation>[] annotationTypes; private final ConcurrentMap<String, AbstractAnnotationBeanPostProcessor.AnnotatedInjectionMetadata> injectionMetadataCache = new ConcurrentHashMap<>(CACHE_SIZE); private ConfigurableListableBeanFactory beanFactory; private Environment environment; private ClassLoader classLoader; private int order = Ordered.LOWEST_PRECEDENCE; /** * @param annotationTypes the multiple types of {@link Annotation annotations} */ public AbstractAnnotationBeanPostProcessor(Class<? extends Annotation>... annotationTypes) { Assert.notEmpty(annotationTypes, "The argument of annotations' types must not empty"); this.annotationTypes = annotationTypes; } private static <T> Collection<T> combine(Collection<? extends T>... elements) { List<T> allElements = new ArrayList<>(); for (Collection<? extends T> e : elements) { allElements.addAll(e); } return allElements; } /** * Annotation type * * @return non-null * @deprecated 2.7.3, uses {@link #getAnnotationTypes()} */ @Deprecated public final Class<? extends Annotation> getAnnotationType() { return annotationTypes[0]; } protected final Class<? extends Annotation>[] getAnnotationTypes() { return annotationTypes; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { Assert.isInstanceOf( ConfigurableListableBeanFactory.class, beanFactory, "AnnotationInjectedBeanPostProcessor requires a ConfigurableListableBeanFactory"); this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } /** * Finds {@link InjectionMetadata.InjectedElement} Metadata from annotated fields * * @param beanClass The {@link Class} of Bean * @return non-null {@link List} */ private List<AbstractAnnotationBeanPostProcessor.AnnotatedFieldElement> findFieldAnnotationMetadata( final Class<?> beanClass) { final List<AbstractAnnotationBeanPostProcessor.AnnotatedFieldElement> elements = new LinkedList<>(); ReflectionUtils.doWithFields(beanClass, field -> { for (Class<? extends Annotation> annotationType : getAnnotationTypes()) { AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes(field, annotationType, getEnvironment(), true, true); if (attributes != null) { if (Modifier.isStatic(field.getModifiers())) { if (logger.isWarnEnabled()) { logger.warn( CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "@" + annotationType.getName() + " is not supported on static fields: " + field); } return; } elements.add(new AnnotatedFieldElement(field, attributes)); } } }); return elements; } /** * Finds {@link InjectionMetadata.InjectedElement} Metadata from annotated methods * * @param beanClass The {@link Class} of Bean * @return non-null {@link List} */ private List<AbstractAnnotationBeanPostProcessor.AnnotatedMethodElement> findAnnotatedMethodMetadata( final Class<?> beanClass) { final List<AbstractAnnotationBeanPostProcessor.AnnotatedMethodElement> elements = new LinkedList<>(); ReflectionUtils.doWithMethods(beanClass, method -> { Method bridgedMethod = findBridgedMethod(method); if (!isVisibilityBridgeMethodPair(method, bridgedMethod)) { return; } if (method.getAnnotation(Bean.class) != null) { // DO NOT inject to Java-config class's @Bean method return; } for (Class<? extends Annotation> annotationType : getAnnotationTypes()) { AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes( bridgedMethod, annotationType, getEnvironment(), true, true); if (attributes != null && method.equals(ClassUtils.getMostSpecificMethod(method, beanClass))) { if (Modifier.isStatic(method.getModifiers())) { throw new IllegalStateException("When using @" + annotationType.getName() + " to inject interface proxy, it is not supported on static methods: " + method); } if (method.getParameterTypes().length != 1) { throw new IllegalStateException("When using @" + annotationType.getName() + " to inject interface proxy, the method must have only one parameter: " + method); } PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, beanClass); elements.add(new AnnotatedMethodElement(method, pd, attributes)); } } }); return elements; } private AbstractAnnotationBeanPostProcessor.AnnotatedInjectionMetadata buildAnnotatedMetadata( final Class<?> beanClass) { Collection<AbstractAnnotationBeanPostProcessor.AnnotatedFieldElement> fieldElements = findFieldAnnotationMetadata(beanClass); Collection<AbstractAnnotationBeanPostProcessor.AnnotatedMethodElement> methodElements = findAnnotatedMethodMetadata(beanClass); return new AnnotatedInjectionMetadata(beanClass, fieldElements, methodElements); } protected AnnotatedInjectionMetadata findInjectionMetadata(String beanName, Class<?> clazz, PropertyValues pvs) { // Fall back to class name as cache key, for backwards compatibility with custom callers. String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName()); // Quick check on the concurrent map first, with minimal locking. AbstractAnnotationBeanPostProcessor.AnnotatedInjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey); if (needsRefreshInjectionMetadata(metadata, clazz)) { synchronized (this.injectionMetadataCache) { metadata = this.injectionMetadataCache.get(cacheKey); if (needsRefreshInjectionMetadata(metadata, clazz)) { if (metadata != null) { metadata.clear(pvs); } try { metadata = buildAnnotatedMetadata(clazz); this.injectionMetadataCache.put(cacheKey, metadata); } catch (NoClassDefFoundError err) { throw new IllegalStateException( "Failed to introspect object class [" + clazz.getName() + "] for annotation metadata: could not find class that it depends on", err); } } } } return metadata; } // Use custom check method to compatible with Spring 4.x private boolean needsRefreshInjectionMetadata(AnnotatedInjectionMetadata metadata, Class<?> clazz) { return (metadata == null || metadata.needsRefresh(clazz)); } @Override public void destroy() throws Exception { injectionMetadataCache.clear(); if (logger.isInfoEnabled()) { logger.info(getClass() + " was destroying!"); } } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } @Override public void setEnvironment(Environment environment) { this.environment = environment; } protected Environment getEnvironment() { return environment; } protected ClassLoader getClassLoader() { return classLoader; } protected ConfigurableListableBeanFactory getBeanFactory() { return beanFactory; } /** * Get injected-object from specified {@link AnnotationAttributes annotation attributes} and Bean Class * * @param attributes {@link AnnotationAttributes the annotation attributes} * @param bean Current bean that will be injected * @param beanName Current bean name that will be injected * @param injectedType the type of injected-object * @param injectedElement {@link AnnotatedInjectElement} * @return An injected object * @throws Exception If getting is failed */ protected Object getInjectedObject( AnnotationAttributes attributes, Object bean, String beanName, Class<?> injectedType, AnnotatedInjectElement injectedElement) throws Exception { return doGetInjectedBean(attributes, bean, beanName, injectedType, injectedElement); } /** * Prepare injection data after found injection elements * * @param metadata * @throws Exception */ protected void prepareInjection(AnnotatedInjectionMetadata metadata) throws Exception {} /** * Subclass must implement this method to get injected-object. The context objects could help this method if * necessary : * <ul> * <li>{@link #getBeanFactory() BeanFactory}</li> * <li>{@link #getClassLoader() ClassLoader}</li> * <li>{@link #getEnvironment() Environment}</li> * </ul> * * @param attributes {@link AnnotationAttributes the annotation attributes} * @param bean Current bean that will be injected * @param beanName Current bean name that will be injected * @param injectedType the type of injected-object * @param injectedElement {@link AnnotatedInjectElement} * @return The injected object * @throws Exception If resolving an injected object is failed. */ protected abstract Object doGetInjectedBean( AnnotationAttributes attributes, Object bean, String beanName, Class<?> injectedType, AnnotatedInjectElement injectedElement) throws Exception; @Override public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException { return null; } @Override public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { return true; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } /** * {@link Annotation Annotated} {@link InjectionMetadata} implementation */ protected static class AnnotatedInjectionMetadata extends InjectionMetadata { private Class<?> targetClass; private final Collection<AbstractAnnotationBeanPostProcessor.AnnotatedFieldElement> fieldElements; private final Collection<AbstractAnnotationBeanPostProcessor.AnnotatedMethodElement> methodElements; public AnnotatedInjectionMetadata( Class<?> targetClass, Collection<AbstractAnnotationBeanPostProcessor.AnnotatedFieldElement> fieldElements, Collection<AbstractAnnotationBeanPostProcessor.AnnotatedMethodElement> methodElements) { super(targetClass, combine(fieldElements, methodElements)); this.targetClass = targetClass; this.fieldElements = fieldElements; this.methodElements = methodElements; } public Collection<AbstractAnnotationBeanPostProcessor.AnnotatedFieldElement> getFieldElements() { return fieldElements; } public Collection<AbstractAnnotationBeanPostProcessor.AnnotatedMethodElement> getMethodElements() { return methodElements; } // @Override // since Spring 5.2.4 protected boolean needsRefresh(Class<?> clazz) { if (this.targetClass == clazz) { return false; } // IGNORE Spring CGLIB enhanced class if (targetClass.isAssignableFrom(clazz) && clazz.getName().contains("$$EnhancerBySpringCGLIB$$")) { return false; } if (targetClass.isAssignableFrom(clazz) && clazz.getName().contains("$$SpringCGLIB$$")) { return false; } return true; } } /** * {@link Annotation Annotated} {@link Method} {@link InjectionMetadata.InjectedElement} */ protected class AnnotatedInjectElement extends InjectionMetadata.InjectedElement { public final AnnotationAttributes attributes; public volatile Object injectedObject; public Class<?> injectedType; protected AnnotatedInjectElement(Member member, PropertyDescriptor pd, AnnotationAttributes attributes) { super(member, pd); this.attributes = attributes; } @Override protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable { Object injectedObject = getInjectedObject(attributes, bean, beanName, getInjectedType(), this); if (member instanceof Field) { Field field = (Field) member; ReflectionUtils.makeAccessible(field); field.set(bean, injectedObject); } else if (member instanceof Method) { Method method = (Method) member; ReflectionUtils.makeAccessible(method); method.invoke(bean, injectedObject); } } public Class<?> getInjectedType() throws ClassNotFoundException { if (injectedType == null) { if (this.isField) { injectedType = ((Field) this.member).getType(); } else if (this.pd != null) { return this.pd.getPropertyType(); } else { Method method = (Method) this.member; if (method.getParameterTypes().length > 0) { injectedType = method.getParameterTypes()[0]; } else { throw new IllegalStateException("get injected type failed"); } } } return injectedType; } public String getPropertyName() { if (member instanceof Field) { Field field = (Field) member; return field.getName(); } else if (this.pd != null) { // If it is method element, using propertyName of PropertyDescriptor return pd.getName(); } else { Method method = (Method) this.member; return method.getName(); } } } protected class AnnotatedMethodElement extends AnnotatedInjectElement { public final Method method; protected AnnotatedMethodElement(Method method, PropertyDescriptor pd, AnnotationAttributes attributes) { super(method, pd, attributes); this.method = method; } } public class AnnotatedFieldElement extends AnnotatedInjectElement { public final Field field; protected AnnotatedFieldElement(Field field, AnnotationAttributes attributes) { super(field, null, attributes); this.field = field; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.beans.factory.annotation; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.ArrayUtils; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.DubboReference; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.spring.Constants; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.aot.AotWithSpringDetector; import org.apache.dubbo.config.spring.context.event.DubboConfigInitEvent; import org.apache.dubbo.config.spring.reference.ReferenceAttributes; import org.apache.dubbo.config.spring.reference.ReferenceBeanManager; import org.apache.dubbo.config.spring.reference.ReferenceBeanSupport; import org.apache.dubbo.config.spring.util.AnnotationUtils; import org.apache.dubbo.config.spring.util.SpringCompatUtils; import org.apache.dubbo.rpc.service.GenericService; import java.beans.PropertyDescriptor; import java.lang.annotation.Annotation; import java.lang.reflect.Member; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.annotation.InjectionMetadata; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.AbstractBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.MethodMetadata; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; import static org.apache.dubbo.common.utils.AnnotationUtils.filterDefaultValues; import static org.springframework.util.StringUtils.hasText; /** * <p> * Step 1: * The purpose of implementing {@link BeanFactoryPostProcessor} is to scan the registration reference bean definition earlier, * so that it can be shared with the xml bean configuration. * </p> * * <p> * Step 2: * By implementing {@link org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor}, * inject the reference bean instance into the fields and setter methods which annotated with {@link DubboReference}. * </p> * * @see DubboReference * @see Reference * @see com.alibaba.dubbo.config.annotation.Reference * @since 2.5.7 */ public class ReferenceAnnotationBeanPostProcessor extends AbstractAnnotationBeanPostProcessor implements ApplicationContextAware, BeanFactoryPostProcessor { /** * The bean name of {@link ReferenceAnnotationBeanPostProcessor} */ public static final String BEAN_NAME = ReferenceAnnotationBeanPostProcessor.class.getName(); /** * Cache size */ private static final int CACHE_SIZE = Integer.getInteger(BEAN_NAME + ".cache.size", 32); private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); private final ConcurrentMap<InjectionMetadata.InjectedElement, String> injectedFieldReferenceBeanCache = new ConcurrentHashMap<>(CACHE_SIZE); private final ConcurrentMap<InjectionMetadata.InjectedElement, String> injectedMethodReferenceBeanCache = new ConcurrentHashMap<>(CACHE_SIZE); protected ApplicationContext applicationContext; protected ReferenceBeanManager referenceBeanManager; protected BeanDefinitionRegistry beanDefinitionRegistry; /** * {@link com.alibaba.dubbo.config.annotation.Reference @com.alibaba.dubbo.config.annotation.Reference} has been supported since 2.7.3 * <p> * {@link DubboReference @DubboReference} has been supported since 2.7.7 */ public ReferenceAnnotationBeanPostProcessor() { super(loadAnnotationTypes()); } @SuppressWarnings("unchecked") private static Class<? extends Annotation>[] loadAnnotationTypes() { if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isReferenceClassLoaded()) { return (Class<? extends Annotation>[]) new Class<?>[] {DubboReference.class, Reference.class, Dubbo2CompactUtils.getReferenceClass()}; } else { return (Class<? extends Annotation>[]) new Class<?>[] {DubboReference.class, Reference.class}; } } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { String[] beanNames = beanFactory.getBeanDefinitionNames(); for (String beanName : beanNames) { Class<?> beanType; if (beanFactory.isFactoryBean(beanName)) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); if (isReferenceBean(beanDefinition)) { continue; } if (isAnnotatedReferenceBean(beanDefinition)) { // process @DubboReference at java-config @bean method processReferenceAnnotatedBeanDefinition(beanName, (AnnotatedBeanDefinition) beanDefinition); continue; } String beanClassName = beanDefinition.getBeanClassName(); beanType = ClassUtils.resolveClass(beanClassName, getClassLoader()); } else { beanType = beanFactory.getType(beanName); } if (beanType != null) { AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanName, beanType, null); try { prepareInjection(metadata); } catch (BeansException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Prepare dubbo reference injection element failed", e); } } } if (beanFactory instanceof AbstractBeanFactory) { List<BeanPostProcessor> beanPostProcessors = ((AbstractBeanFactory) beanFactory).getBeanPostProcessors(); for (BeanPostProcessor beanPostProcessor : beanPostProcessors) { if (beanPostProcessor == this) { // This bean has been registered as BeanPostProcessor at // org.apache.dubbo.config.spring.context.DubboInfraBeanRegisterPostProcessor.postProcessBeanFactory() // so destroy this bean here, prevent register it as BeanPostProcessor again, avoid cause // BeanPostProcessorChecker detection error beanDefinitionRegistry.removeBeanDefinition(BEAN_NAME); break; } } } try { // this is an early event, it will be notified at // org.springframework.context.support.AbstractApplicationContext.registerListeners() applicationContext.publishEvent(new DubboConfigInitEvent(applicationContext)); } catch (Exception e) { // if spring version is less than 4.2, it does not support early application event logger.warn( CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "publish early application event failed, please upgrade spring version to 4.2.x or later: " + e); } } /** * check whether is @DubboReference at java-config @bean method */ private boolean isAnnotatedReferenceBean(BeanDefinition beanDefinition) { if (beanDefinition instanceof AnnotatedBeanDefinition) { AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition; String beanClassName = SpringCompatUtils.getFactoryMethodReturnType(annotatedBeanDefinition); if (beanClassName != null && ReferenceBean.class.getName().equals(beanClassName)) { return true; } } return false; } /** * process @DubboReference at java-config @bean method * <pre class="code"> * &#064;Configuration * public class ConsumerConfig { * * &#064;Bean * &#064;DubboReference(group="demo", version="1.2.3") * public ReferenceBean&lt;DemoService&gt; demoService() { * return new ReferenceBean(); * } * * } * </pre> * * @param beanName * @param beanDefinition */ protected void processReferenceAnnotatedBeanDefinition(String beanName, AnnotatedBeanDefinition beanDefinition) { MethodMetadata factoryMethodMetadata = SpringCompatUtils.getFactoryMethodMetadata(beanDefinition); // Extract beanClass from generic return type of java-config bean method: ReferenceBean<DemoService> // see // org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryBeanFromMethod Class beanClass = getBeanFactory().getType(beanName); if (beanClass == Object.class) { beanClass = SpringCompatUtils.getGenericTypeOfReturnType(factoryMethodMetadata); } if (beanClass == Object.class) { // bean class is invalid, ignore it return; } if (beanClass == null) { String beanMethodSignature = factoryMethodMetadata.getDeclaringClassName() + "#" + factoryMethodMetadata.getMethodName() + "()"; throw new BeanCreationException( "The ReferenceBean is missing necessary generic type, which returned by the @Bean method of Java-config class. " + "The generic type of the returned ReferenceBean must be specified as the referenced interface type, " + "such as ReferenceBean<DemoService>. Please check bean method: " + beanMethodSignature); } // get dubbo reference annotation attributes Map<String, Object> annotationAttributes = null; // try all dubbo reference annotation types for (Class<? extends Annotation> annotationType : getAnnotationTypes()) { if (factoryMethodMetadata.isAnnotated(annotationType.getName())) { // Since Spring 5.2 // return factoryMethodMetadata.getAnnotations().get(annotationType).filterDefaultValues().asMap(); // Compatible with Spring 4.x annotationAttributes = factoryMethodMetadata.getAnnotationAttributes(annotationType.getName()); annotationAttributes = filterDefaultValues(annotationType, annotationAttributes); break; } } if (annotationAttributes != null) { // @DubboReference on @Bean method LinkedHashMap<String, Object> attributes = new LinkedHashMap<>(annotationAttributes); // reset id attribute attributes.put(ReferenceAttributes.ID, beanName); // convert annotation props ReferenceBeanSupport.convertReferenceProps(attributes, beanClass); // get interface String interfaceName = (String) attributes.get(ReferenceAttributes.INTERFACE); // check beanClass and reference interface class if (!StringUtils.isEquals(interfaceName, beanClass.getName()) && beanClass != GenericService.class) { String beanMethodSignature = factoryMethodMetadata.getDeclaringClassName() + "#" + factoryMethodMetadata.getMethodName() + "()"; throw new BeanCreationException( "The 'interfaceClass' or 'interfaceName' attribute value of @DubboReference annotation " + "is inconsistent with the generic type of the ReferenceBean returned by the bean method. " + "The interface class of @DubboReference is: " + interfaceName + ", but return ReferenceBean<" + beanClass.getName() + ">. " + "Please remove the 'interfaceClass' and 'interfaceName' attributes from @DubboReference annotation. " + "Please check bean method: " + beanMethodSignature); } Class interfaceClass = beanClass; // set attribute instead of property values beanDefinition.setAttribute(Constants.REFERENCE_PROPS, attributes); beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_CLASS, interfaceClass); beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_NAME, interfaceName); } else { // raw reference bean // the ReferenceBean is not yet initialized beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_CLASS, beanClass); if (beanClass != GenericService.class) { beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_NAME, beanClass.getName()); } } // set id beanDefinition.getPropertyValues().add(ReferenceAttributes.ID, beanName); } @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { if (beanType != null) { if (isReferenceBean(beanDefinition)) { // mark property value as optional List<PropertyValue> propertyValues = beanDefinition.getPropertyValues().getPropertyValueList(); for (PropertyValue propertyValue : propertyValues) { propertyValue.setOptional(true); } } else if (isAnnotatedReferenceBean(beanDefinition)) { // extract beanClass from java-config bean method generic return type: ReferenceBean<DemoService> // Class beanClass = getBeanFactory().getType(beanName); } else { AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanName, beanType, null); metadata.checkConfigMembers(beanDefinition); try { prepareInjection(metadata); } catch (Exception e) { throw new IllegalStateException("Prepare dubbo reference injection element failed", e); } } } } /** * Alternatives to the {@link #postProcessProperties(PropertyValues, Object, String)}, that removed as of Spring * Framework 6.0.0, and in favor of {@link #postProcessProperties(PropertyValues, Object, String)}. * <p>In order to be compatible with the lower version of Spring, it is still retained. * * @see #postProcessProperties */ public PropertyValues postProcessPropertyValues( PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException { return postProcessProperties(pvs, bean, beanName); } /** * Alternatives to the {@link #postProcessPropertyValues(PropertyValues, PropertyDescriptor[], Object, String)}. * * @see #postProcessPropertyValues */ @Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException { try { AnnotatedInjectionMetadata metadata = findInjectionMetadata(beanName, bean.getClass(), pvs); prepareInjection(metadata); metadata.inject(bean, beanName, pvs); } catch (BeansException ex) { throw ex; } catch (Throwable ex) { throw new BeanCreationException( beanName, "Injection of @" + getAnnotationType().getSimpleName() + " dependencies is failed", ex); } return pvs; } private boolean isReferenceBean(BeanDefinition beanDefinition) { return ReferenceBean.class.getName().equals(beanDefinition.getBeanClassName()); } protected void prepareInjection(AnnotatedInjectionMetadata metadata) throws BeansException { try { // find and register bean definition for @DubboReference/@Reference for (AnnotatedFieldElement fieldElement : metadata.getFieldElements()) { if (fieldElement.injectedObject != null) { continue; } Class<?> injectedType = fieldElement.field.getType(); AnnotationAttributes attributes = fieldElement.attributes; String referenceBeanName = registerReferenceBean( fieldElement.getPropertyName(), injectedType, attributes, fieldElement.field); // associate fieldElement and reference bean fieldElement.injectedObject = referenceBeanName; injectedFieldReferenceBeanCache.put(fieldElement, referenceBeanName); } for (AnnotatedMethodElement methodElement : metadata.getMethodElements()) { if (methodElement.injectedObject != null) { continue; } Class<?> injectedType = methodElement.getInjectedType(); AnnotationAttributes attributes = methodElement.attributes; String referenceBeanName = registerReferenceBean( methodElement.getPropertyName(), injectedType, attributes, methodElement.method); // associate methodElement and reference bean methodElement.injectedObject = referenceBeanName; injectedMethodReferenceBeanCache.put(methodElement, referenceBeanName); } } catch (ClassNotFoundException e) { throw new BeanCreationException("prepare reference annotation failed", e); } } public String registerReferenceBean( String propertyName, Class<?> injectedType, Map<String, Object> attributes, Member member) throws BeansException { boolean renameable = true; // referenceBeanName String referenceBeanName = AnnotationUtils.getAttribute(attributes, ReferenceAttributes.ID); if (hasText(referenceBeanName)) { renameable = false; } else { referenceBeanName = propertyName; } String checkLocation = "Please check " + member.toString(); // convert annotation props ReferenceBeanSupport.convertReferenceProps(attributes, injectedType); // get interface String interfaceName = (String) attributes.get(ReferenceAttributes.INTERFACE); if (StringUtils.isBlank(interfaceName)) { throw new BeanCreationException( "Need to specify the 'interfaceName' or 'interfaceClass' attribute of '@DubboReference' if enable generic. " + checkLocation); } // check reference key String referenceKey = ReferenceBeanSupport.generateReferenceKey(attributes, applicationContext); // find reference bean name by reference key List<String> registeredReferenceBeanNames = referenceBeanManager.getBeanNamesByKey(referenceKey); if (registeredReferenceBeanNames.size() > 0) { // found same name and reference key if (registeredReferenceBeanNames.contains(referenceBeanName)) { return referenceBeanName; } } // check bean definition boolean isContains; if ((isContains = beanDefinitionRegistry.containsBeanDefinition(referenceBeanName)) || beanDefinitionRegistry.isAlias(referenceBeanName)) { String preReferenceBeanName = referenceBeanName; if (!isContains) { // Look in the alias for the origin bean name String[] aliases = beanDefinitionRegistry.getAliases(referenceBeanName); if (ArrayUtils.isNotEmpty(aliases)) { for (String alias : aliases) { if (beanDefinitionRegistry.containsBeanDefinition(alias)) { preReferenceBeanName = alias; break; } } } } BeanDefinition prevBeanDefinition = beanDefinitionRegistry.getBeanDefinition(preReferenceBeanName); String prevBeanType = prevBeanDefinition.getBeanClassName(); String prevBeanDesc = referenceBeanName + "[" + prevBeanType + "]"; String newBeanDesc = referenceBeanName + "[" + referenceKey + "]"; if (isReferenceBean(prevBeanDefinition)) { // check reference key String prevReferenceKey = ReferenceBeanSupport.generateReferenceKey(prevBeanDefinition, applicationContext); if (StringUtils.isEquals(prevReferenceKey, referenceKey)) { // found matched dubbo reference bean, ignore register return referenceBeanName; } // get interfaceName from attribute Assert.notNull(prevBeanDefinition, "The interface class of ReferenceBean is not initialized"); prevBeanDesc = referenceBeanName + "[" + prevReferenceKey + "]"; } // bean name from attribute 'id' or java-config bean, cannot be renamed if (!renameable) { throw new BeanCreationException( "Already exists another bean definition with the same bean name [" + referenceBeanName + "], " + "but cannot rename the reference bean name (specify the id attribute or java-config bean), " + "please modify the name of one of the beans: " + "prev: " + prevBeanDesc + ", new: " + newBeanDesc + ". " + checkLocation); } // the prev bean type is different, rename the new reference bean int index = 2; String newReferenceBeanName = null; while (newReferenceBeanName == null || beanDefinitionRegistry.containsBeanDefinition(newReferenceBeanName) || beanDefinitionRegistry.isAlias(newReferenceBeanName)) { newReferenceBeanName = referenceBeanName + "#" + index; index++; // double check found same name and reference key if (registeredReferenceBeanNames.contains(newReferenceBeanName)) { return newReferenceBeanName; } } newBeanDesc = newReferenceBeanName + "[" + referenceKey + "]"; logger.warn( CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "Already exists another bean definition with the same bean name [" + referenceBeanName + "], " + "rename dubbo reference bean to [" + newReferenceBeanName + "]. " + "It is recommended to modify the name of one of the beans to avoid injection problems. " + "prev: " + prevBeanDesc + ", new: " + newBeanDesc + ". " + checkLocation); referenceBeanName = newReferenceBeanName; } attributes.put(ReferenceAttributes.ID, referenceBeanName); // If registered matched reference before, just register alias if (registeredReferenceBeanNames.size() > 0) { beanDefinitionRegistry.registerAlias(registeredReferenceBeanNames.get(0), referenceBeanName); referenceBeanManager.registerReferenceKeyAndBeanName(referenceKey, referenceBeanName); return referenceBeanName; } Class interfaceClass = injectedType; // TODO Only register one reference bean for same (group, interface, version) // Register the reference bean definition to the beanFactory RootBeanDefinition beanDefinition = new RootBeanDefinition(); beanDefinition.setBeanClassName(ReferenceBean.class.getName()); beanDefinition.getPropertyValues().add(ReferenceAttributes.ID, referenceBeanName); // set attribute instead of property values beanDefinition.setAttribute(Constants.REFERENCE_PROPS, attributes); beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_CLASS, interfaceClass); beanDefinition.setAttribute(ReferenceAttributes.INTERFACE_NAME, interfaceName); beanDefinition.getPropertyValues().add(ReferenceAttributes.INTERFACE_CLASS, interfaceClass); beanDefinition.getPropertyValues().add(ReferenceAttributes.INTERFACE_NAME, interfaceName); if (AotWithSpringDetector.isAotProcessing()) { beanDefinition.getPropertyValues().add("referencePropsJson", JsonUtils.toJson(attributes)); } // create decorated definition for reference bean, Avoid being instantiated when getting the beanType of // ReferenceBean // see org.springframework.beans.factory.support.AbstractBeanFactory#getTypeForFactoryBean() GenericBeanDefinition targetDefinition = new GenericBeanDefinition(); targetDefinition.setBeanClass(interfaceClass); beanDefinition.setDecoratedDefinition( new BeanDefinitionHolder(targetDefinition, referenceBeanName + "_decorated")); // signal object type since Spring 5.2 beanDefinition.setAttribute(Constants.OBJECT_TYPE_ATTRIBUTE, interfaceClass); beanDefinitionRegistry.registerBeanDefinition(referenceBeanName, beanDefinition); referenceBeanManager.registerReferenceKeyAndBeanName(referenceKey, referenceBeanName); logger.info("Register dubbo reference bean: " + referenceBeanName + " = " + referenceKey + " at " + member); return referenceBeanName; } @Override protected Object doGetInjectedBean( AnnotationAttributes attributes, Object bean, String beanName, Class<?> injectedType, AnnotatedInjectElement injectedElement) throws Exception { if (injectedElement.injectedObject == null) { throw new IllegalStateException( "The AnnotatedInjectElement of @DubboReference should be inited before injection"); } return getBeanFactory().getBean((String) injectedElement.injectedObject); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; this.referenceBeanManager = applicationContext.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class); this.beanDefinitionRegistry = (BeanDefinitionRegistry) applicationContext.getAutowireCapableBeanFactory(); } @Override public void destroy() throws Exception { super.destroy(); this.injectedFieldReferenceBeanCache.clear(); this.injectedMethodReferenceBeanCache.clear(); } /** * Gets all beans of {@link ReferenceBean} * * @deprecated use {@link ReferenceBeanManager#getReferences()} instead */ @Deprecated public Collection<ReferenceBean<?>> getReferenceBeans() { return Collections.emptyList(); } /** * Get {@link ReferenceBean} {@link Map} in injected field. * * @return non-null {@link Map} * @since 2.5.11 */ public Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> getInjectedFieldReferenceBeanMap() { Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> map = new HashMap<>(); for (Map.Entry<InjectionMetadata.InjectedElement, String> entry : injectedFieldReferenceBeanCache.entrySet()) { map.put(entry.getKey(), referenceBeanManager.getById(entry.getValue())); } return Collections.unmodifiableMap(map); } /** * Get {@link ReferenceBean} {@link Map} in injected method. * * @return non-null {@link Map} * @since 2.5.11 */ public Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> getInjectedMethodReferenceBeanMap() { Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> map = new HashMap<>(); for (Map.Entry<InjectionMetadata.InjectedElement, String> entry : injectedMethodReferenceBeanCache.entrySet()) { map.put(entry.getKey(), referenceBeanManager.getById(entry.getValue())); } return Collections.unmodifiableMap(map); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigAliasPostProcessor.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigAliasPostProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.beans.factory.annotation; import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.config.spring.context.annotation.DubboConfigConfigurationRegistrar; import org.apache.dubbo.config.spring.util.BeanRegistrar; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; import static org.springframework.util.ObjectUtils.nullSafeEquals; import static org.springframework.util.StringUtils.hasText; /** * A Post-Processor class to set the alias of Dubbo Config bean using its {@link AbstractConfig#getId()} * * @since 2.7.5 */ public class DubboConfigAliasPostProcessor implements BeanDefinitionRegistryPostProcessor, BeanPostProcessor { /** * The bean name of {@link DubboConfigConfigurationRegistrar} */ public static final String BEAN_NAME = "dubboConfigAliasPostProcessor"; private BeanDefinitionRegistry registry; @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { this.registry = registry; } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { // DO NOTHING } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { // DO NOTHING return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof AbstractConfig) { String id = ((AbstractConfig) bean).getId(); if (hasText(id) // id MUST be present in AbstractConfig && !nullSafeEquals(id, beanName) // id MUST NOT be equal to bean name && !BeanRegistrar.hasAlias(registry, beanName, id)) { // id MUST NOT be present in AliasRegistry registry.registerAlias(beanName, id); } } return bean; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.beans.factory.annotation; import org.apache.dubbo.common.compact.Dubbo2CompactUtils; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.AnnotationUtils; import org.apache.dubbo.common.utils.ClassUtils; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.Constants; import org.apache.dubbo.config.MethodConfig; import org.apache.dubbo.config.annotation.DubboService; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.annotation.Service; import org.apache.dubbo.config.spring.ServiceBean; import org.apache.dubbo.config.spring.aot.AotWithSpringDetector; import org.apache.dubbo.config.spring.context.annotation.DubboClassPathBeanDefinitionScanner; import org.apache.dubbo.config.spring.schema.AnnotationBeanDefinitionParser; import org.apache.dubbo.config.spring.util.DubboAnnotationUtils; import org.apache.dubbo.config.spring.util.ObjectUtils; import org.apache.dubbo.config.spring.util.SpringCompatUtils; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.SingletonBeanRegistry; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; import org.springframework.beans.factory.support.BeanNameGenerator; import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.EnvironmentAware; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.AnnotationBeanNameGenerator; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import org.springframework.context.annotation.ConfigurationClassPostProcessor; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; import org.springframework.core.type.MethodMetadata; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.core.type.filter.TypeFilter; import org.springframework.util.CollectionUtils; import static java.util.Arrays.asList; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUPLICATED_BEAN_DEFINITION; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NO_ANNOTATIONS_FOUND; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NO_BEANS_SCANNED; import static org.apache.dubbo.common.utils.AnnotationUtils.filterDefaultValues; import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilder.create; import static org.apache.dubbo.config.spring.util.DubboAnnotationUtils.resolveInterfaceName; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition; import static org.springframework.context.annotation.AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR; import static org.springframework.util.ClassUtils.resolveClassName; /** * A {@link BeanFactoryPostProcessor} used for processing of {@link Service @Service} annotated classes and annotated bean in java config classes. * It's also the infrastructure class of XML {@link BeanDefinitionParser} on &lt;dubbo:annotation /&gt; * * @see AnnotationBeanDefinitionParser * @see BeanDefinitionRegistryPostProcessor * @since 2.7.7 */ public class ServiceAnnotationPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware, ResourceLoaderAware, BeanClassLoaderAware, ApplicationContextAware, InitializingBean { public static final String BEAN_NAME = "dubboServiceAnnotationPostProcessor"; private static final List<Class<? extends Annotation>> serviceAnnotationTypes = loadServiceAnnotationTypes(); private static List<Class<? extends Annotation>> loadServiceAnnotationTypes() { if (Dubbo2CompactUtils.isEnabled() && Dubbo2CompactUtils.isServiceClassLoaded()) { return asList( // @since 2.7.7 Add the @DubboService , the issue : https://github.com/apache/dubbo/issues/6007 DubboService.class, // @since 2.7.0 the substitute @com.alibaba.dubbo.config.annotation.Service Service.class, // @since 2.7.3 Add the compatibility for legacy Dubbo's @Service , the issue : // https://github.com/apache/dubbo/issues/4330 Dubbo2CompactUtils.getServiceClass()); } else { return asList( // @since 2.7.7 Add the @DubboService , the issue : https://github.com/apache/dubbo/issues/6007 DubboService.class, // @since 2.7.0 the substitute @com.alibaba.dubbo.config.annotation.Service Service.class); } } private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); protected final Set<String> packagesToScan; private Set<String> resolvedPackagesToScan; private Environment environment; private ResourceLoader resourceLoader; private ClassLoader classLoader; private BeanDefinitionRegistry registry; protected ServicePackagesHolder servicePackagesHolder; private volatile boolean scanned = false; public ServiceAnnotationPostProcessor(String... packagesToScan) { this(asList(packagesToScan)); } public ServiceAnnotationPostProcessor(Collection<?> packagesToScan) { this.packagesToScan = (Set<String>) packagesToScan.stream().collect(Collectors.toSet()); } @Override public void afterPropertiesSet() throws Exception { this.resolvedPackagesToScan = resolvePackagesToScan(packagesToScan); } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { this.registry = registry; scanServiceBeans(resolvedPackagesToScan, registry); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (this.registry == null) { // In spring 3.x, may be not call postProcessBeanDefinitionRegistry() this.registry = (BeanDefinitionRegistry) beanFactory; } // scan bean definitions String[] beanNames = beanFactory.getBeanDefinitionNames(); for (String beanName : beanNames) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); Map<String, Object> annotationAttributes = getServiceAnnotationAttributes(beanDefinition); if (annotationAttributes != null) { // process @DubboService at java-config @bean method processAnnotatedBeanDefinition( beanName, (AnnotatedBeanDefinition) beanDefinition, annotationAttributes); } } if (!scanned) { // In spring 3.x, may be not call postProcessBeanDefinitionRegistry(), so scan service class here scanServiceBeans(resolvedPackagesToScan, registry); } } /** * Scan and registers service beans whose classes was annotated {@link Service} * * @param packagesToScan The base packages to scan * @param registry {@link BeanDefinitionRegistry} */ private void scanServiceBeans(Set<String> packagesToScan, BeanDefinitionRegistry registry) { scanned = true; if (CollectionUtils.isEmpty(packagesToScan)) { if (logger.isWarnEnabled()) { logger.warn( CONFIG_NO_BEANS_SCANNED, "", "", "packagesToScan is empty , ServiceBean registry will be ignored!"); } return; } DubboClassPathBeanDefinitionScanner scanner = new DubboClassPathBeanDefinitionScanner(registry, environment, resourceLoader); BeanNameGenerator beanNameGenerator = resolveBeanNameGenerator(registry); scanner.setBeanNameGenerator(beanNameGenerator); for (Class<? extends Annotation> annotationType : serviceAnnotationTypes) { scanner.addIncludeFilter(new AnnotationTypeFilter(annotationType)); } ScanExcludeFilter scanExcludeFilter = new ScanExcludeFilter(); scanner.addExcludeFilter(scanExcludeFilter); for (String packageToScan : packagesToScan) { // avoid duplicated scans if (servicePackagesHolder.isPackageScanned(packageToScan)) { if (logger.isInfoEnabled()) { logger.info("Ignore package who has already bean scanned: " + packageToScan); } continue; } if (AotWithSpringDetector.useGeneratedArtifacts()) { scanner.setIncludeAnnotationConfig(false); } // Registers @Service Bean first scanner.scan(packageToScan); // Finds all BeanDefinitionHolders of @Service whether @ComponentScan scans or not. Set<BeanDefinitionHolder> beanDefinitionHolders = findServiceBeanDefinitionHolders(scanner, packageToScan, registry, beanNameGenerator); if (!CollectionUtils.isEmpty(beanDefinitionHolders)) { if (logger.isInfoEnabled()) { List<String> serviceClasses = new ArrayList<>(beanDefinitionHolders.size()); for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) { serviceClasses.add( beanDefinitionHolder.getBeanDefinition().getBeanClassName()); } logger.info("Found " + beanDefinitionHolders.size() + " classes annotated by Dubbo @Service under package [" + packageToScan + "]: " + serviceClasses); } for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) { processScannedBeanDefinition(beanDefinitionHolder); servicePackagesHolder.addScannedClass( beanDefinitionHolder.getBeanDefinition().getBeanClassName()); } } else { if (logger.isWarnEnabled()) { logger.warn( CONFIG_NO_ANNOTATIONS_FOUND, "No annotations were found on the class", "", "No class annotated by Dubbo @DubboService or @Service was found under package [" + packageToScan + "], ignore re-scanned classes: " + scanExcludeFilter.getExcludedCount()); } } servicePackagesHolder.addScannedPackage(packageToScan); } } /** * It'd be better to use BeanNameGenerator instance that should reference * {@link ConfigurationClassPostProcessor#componentScanBeanNameGenerator}, * thus it maybe a potential problem on bean name generation. * * @param registry {@link BeanDefinitionRegistry} * @return {@link BeanNameGenerator} instance * @see SingletonBeanRegistry * @see AnnotationConfigUtils#CONFIGURATION_BEAN_NAME_GENERATOR * @see ConfigurationClassPostProcessor#processConfigBeanDefinitions * @since 2.5.8 */ private BeanNameGenerator resolveBeanNameGenerator(BeanDefinitionRegistry registry) { BeanNameGenerator beanNameGenerator = null; if (registry instanceof SingletonBeanRegistry) { SingletonBeanRegistry singletonBeanRegistry = SingletonBeanRegistry.class.cast(registry); beanNameGenerator = (BeanNameGenerator) singletonBeanRegistry.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR); } if (beanNameGenerator == null) { if (logger.isInfoEnabled()) { logger.info("BeanNameGenerator bean can't be found in BeanFactory with name [" + CONFIGURATION_BEAN_NAME_GENERATOR + "]"); logger.info("BeanNameGenerator will be a instance of " + AnnotationBeanNameGenerator.class.getName() + " , it maybe a potential problem on bean name generation."); } beanNameGenerator = new AnnotationBeanNameGenerator(); } return beanNameGenerator; } /** * Finds a {@link Set} of {@link BeanDefinitionHolder BeanDefinitionHolders} whose bean type annotated * {@link Service} Annotation. * * @param scanner {@link ClassPathBeanDefinitionScanner} * @param packageToScan package to scan * @param registry {@link BeanDefinitionRegistry} * @return non-null * @since 2.5.8 */ private Set<BeanDefinitionHolder> findServiceBeanDefinitionHolders( ClassPathBeanDefinitionScanner scanner, String packageToScan, BeanDefinitionRegistry registry, BeanNameGenerator beanNameGenerator) { Set<BeanDefinition> beanDefinitions = scanner.findCandidateComponents(packageToScan); Set<BeanDefinitionHolder> beanDefinitionHolders = new LinkedHashSet<>(beanDefinitions.size()); for (BeanDefinition beanDefinition : beanDefinitions) { String beanName = beanNameGenerator.generateBeanName(beanDefinition, registry); BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(beanDefinition, beanName); beanDefinitionHolders.add(beanDefinitionHolder); } return beanDefinitionHolders; } /** * Registers {@link ServiceBean} from new annotated {@link Service} {@link BeanDefinition} * * @param beanDefinitionHolder * @see ServiceBean * @see BeanDefinition */ private void processScannedBeanDefinition(BeanDefinitionHolder beanDefinitionHolder) { Class<?> beanClass = resolveClass(beanDefinitionHolder); Annotation service = findServiceAnnotation(beanClass); // The attributes of @Service annotation Map<String, Object> serviceAnnotationAttributes = AnnotationUtils.getAttributes(service, true); String serviceInterface = resolveInterfaceName(serviceAnnotationAttributes, beanClass); String annotatedServiceBeanName = beanDefinitionHolder.getBeanName(); // ServiceBean Bean name String beanName = generateServiceBeanName(serviceAnnotationAttributes, serviceInterface); AbstractBeanDefinition serviceBeanDefinition = buildServiceBeanDefinition(serviceAnnotationAttributes, serviceInterface, annotatedServiceBeanName); registerServiceBeanDefinition(beanName, serviceBeanDefinition, serviceInterface); } /** * Find the {@link Annotation annotation} of @Service * * @param beanClass the {@link Class class} of Bean * @return <code>null</code> if not found * @since 2.7.3 */ private Annotation findServiceAnnotation(Class<?> beanClass) { return serviceAnnotationTypes.stream() .map(annotationType -> ClassUtils.isPresent( "org.springframework.core.annotation.AnnotatedElementUtils", Thread.currentThread().getContextClassLoader()) && ReflectUtils.hasMethod( org.springframework.core.annotation.AnnotatedElementUtils.class, "findMergedAnnotation") ? org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation( beanClass, annotationType) : org.apache.dubbo.common.utils.AnnotationUtils.findAnnotation(beanClass, annotationType)) .filter(Objects::nonNull) .findFirst() .orElse(null); } /** * Generates the bean name of {@link ServiceBean} * * @param serviceAnnotationAttributes * @param serviceInterface the class of interface annotated {@link Service} * @return ServiceBean@interfaceClassName#annotatedServiceBeanName * @since 2.7.3 */ private String generateServiceBeanName(Map<String, Object> serviceAnnotationAttributes, String serviceInterface) { ServiceBeanNameBuilder builder = create(serviceInterface, environment) .group((String) serviceAnnotationAttributes.get("group")) .version((String) serviceAnnotationAttributes.get("version")); return builder.build(); } private Class<?> resolveClass(BeanDefinitionHolder beanDefinitionHolder) { BeanDefinition beanDefinition = beanDefinitionHolder.getBeanDefinition(); return resolveClass(beanDefinition); } private Class<?> resolveClass(BeanDefinition beanDefinition) { String beanClassName = beanDefinition.getBeanClassName(); return resolveClassName(beanClassName, classLoader); } private Set<String> resolvePackagesToScan(Set<String> packagesToScan) { Set<String> resolvedPackagesToScan = new LinkedHashSet<>(packagesToScan.size()); for (String packageToScan : packagesToScan) { if (StringUtils.hasText(packageToScan)) { String resolvedPackageToScan = environment.resolvePlaceholders(packageToScan.trim()); resolvedPackagesToScan.add(resolvedPackageToScan); } } return resolvedPackagesToScan; } /** * Build the {@link AbstractBeanDefinition Bean Definition} * * @param serviceAnnotationAttributes * @param serviceInterface * @param refServiceBeanName * @return * @since 2.7.3 */ private AbstractBeanDefinition buildServiceBeanDefinition( Map<String, Object> serviceAnnotationAttributes, String serviceInterface, String refServiceBeanName) { BeanDefinitionBuilder builder = rootBeanDefinition(ServiceBean.class); AbstractBeanDefinition beanDefinition = builder.getBeanDefinition(); beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR); MutablePropertyValues propertyValues = beanDefinition.getPropertyValues(); String[] ignoreAttributeNames = ObjectUtils.of( "provider", "monitor", "application", "module", "registry", "protocol", "methods", "interfaceName", "parameters", "executor"); propertyValues.addPropertyValues( new AnnotationPropertyValuesAdapter(serviceAnnotationAttributes, environment, ignoreAttributeNames)); // set config id, for ConfigManager cache key // builder.addPropertyValue("id", beanName); // References "ref" property to annotated-@Service Bean addPropertyReference(builder, "ref", refServiceBeanName); // Set interface builder.addPropertyValue("interface", serviceInterface); // Convert parameters into map builder.addPropertyValue("parameters", DubboAnnotationUtils.convertParameters((String[]) serviceAnnotationAttributes.get("parameters"))); // Add methods parameters List<MethodConfig> methodConfigs = convertMethodConfigs(serviceAnnotationAttributes.get("methods")); if (!methodConfigs.isEmpty()) { if (AotWithSpringDetector.isAotProcessing()) { List<String> methodsJson = new ArrayList<>(); methodConfigs.forEach(methodConfig -> methodsJson.add(JsonUtils.toJson(methodConfig))); builder.addPropertyValue("methodsJson", methodsJson); } else { builder.addPropertyValue("methods", methodConfigs); } } // convert provider to providerIds String providerConfigId = (String) serviceAnnotationAttributes.get("provider"); if (StringUtils.hasText(providerConfigId)) { addPropertyValue(builder, "providerIds", providerConfigId); } // Convert registry[] to registryIds String[] registryConfigIds = (String[]) serviceAnnotationAttributes.get("registry"); if (registryConfigIds != null && registryConfigIds.length > 0) { resolveStringArray(registryConfigIds); builder.addPropertyValue("registryIds", StringUtils.join(registryConfigIds, ',')); } // Convert protocol[] to protocolIds String[] protocolConfigIds = (String[]) serviceAnnotationAttributes.get("protocol"); if (protocolConfigIds != null && protocolConfigIds.length > 0) { resolveStringArray(protocolConfigIds); builder.addPropertyValue("protocolIds", StringUtils.join(protocolConfigIds, ',')); } // TODO Could we ignore these attributes: application/monitor/module ? Use global config // monitor reference String monitorConfigId = (String) serviceAnnotationAttributes.get("monitor"); if (StringUtils.hasText(monitorConfigId)) { addPropertyReference(builder, "monitor", monitorConfigId); } // module reference String moduleConfigId = (String) serviceAnnotationAttributes.get("module"); if (StringUtils.hasText(moduleConfigId)) { addPropertyReference(builder, "module", moduleConfigId); } String executorBeanName = (String) serviceAnnotationAttributes.get("executor"); if (StringUtils.hasText(executorBeanName)) { addPropertyReference(builder, "executor", executorBeanName); } // service bean definition should not be lazy builder.setLazyInit(false); return builder.getBeanDefinition(); } private String[] resolveStringArray(String[] strs) { if (strs == null) { return null; } for (int i = 0; i < strs.length; i++) { strs[i] = environment.resolvePlaceholders(strs[i]); } return strs; } private List convertMethodConfigs(Object methodsAnnotation) { if (methodsAnnotation == null) { return Collections.EMPTY_LIST; } return MethodConfig.constructMethodConfig((Method[]) methodsAnnotation); } private void addPropertyReference(BeanDefinitionBuilder builder, String propertyName, String beanName) { String resolvedBeanName = environment.resolvePlaceholders(beanName); builder.addPropertyReference(propertyName, resolvedBeanName); } private void addPropertyValue(BeanDefinitionBuilder builder, String propertyName, String value) { String resolvedBeanName = environment.resolvePlaceholders(value); builder.addPropertyValue(propertyName, resolvedBeanName); } /** * Get dubbo service annotation class at java-config @bean method * * @return return service annotation attributes map if found, or return null if not found. */ private Map<String, Object> getServiceAnnotationAttributes(BeanDefinition beanDefinition) { if (beanDefinition instanceof AnnotatedBeanDefinition) { AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition; MethodMetadata factoryMethodMetadata = SpringCompatUtils.getFactoryMethodMetadata(annotatedBeanDefinition); if (factoryMethodMetadata != null) { // try all dubbo service annotation types for (Class<? extends Annotation> annotationType : serviceAnnotationTypes) { if (factoryMethodMetadata.isAnnotated(annotationType.getName())) { // Since Spring 5.2 // return // factoryMethodMetadata.getAnnotations().get(annotationType).filterDefaultValues().asMap(); // Compatible with Spring 4.x Map<String, Object> annotationAttributes = factoryMethodMetadata.getAnnotationAttributes(annotationType.getName()); return filterDefaultValues(annotationType, annotationAttributes); } } } } return null; } /** * process @DubboService at java-config @bean method * <pre class="code"> * &#064;Configuration * public class ProviderConfig { * * &#064;Bean * &#064;DubboService(group="demo", version="1.2.3") * public DemoService demoService() { * return new DemoServiceImpl(); * } * * } * </pre> * * @param refServiceBeanName * @param refServiceBeanDefinition * @param attributes */ private void processAnnotatedBeanDefinition( String refServiceBeanName, AnnotatedBeanDefinition refServiceBeanDefinition, Map<String, Object> attributes) { Map<String, Object> serviceAnnotationAttributes = new LinkedHashMap<>(attributes); // get bean class from return type String returnTypeName = SpringCompatUtils.getFactoryMethodReturnType(refServiceBeanDefinition); Class<?> beanClass = resolveClassName(returnTypeName, classLoader); String serviceInterface = resolveInterfaceName(serviceAnnotationAttributes, beanClass); // ServiceBean Bean name String serviceBeanName = generateServiceBeanName(serviceAnnotationAttributes, serviceInterface); AbstractBeanDefinition serviceBeanDefinition = buildServiceBeanDefinition(serviceAnnotationAttributes, serviceInterface, refServiceBeanName); // set id serviceBeanDefinition.getPropertyValues().add(Constants.ID, serviceBeanName); registerServiceBeanDefinition(serviceBeanName, serviceBeanDefinition, serviceInterface); } private void registerServiceBeanDefinition( String serviceBeanName, AbstractBeanDefinition serviceBeanDefinition, String serviceInterface) { // check service bean if (registry.containsBeanDefinition(serviceBeanName)) { BeanDefinition existingDefinition = registry.getBeanDefinition(serviceBeanName); if (existingDefinition.equals(serviceBeanDefinition)) { // exist equipment bean definition return; } String msg = "Found duplicated BeanDefinition of service interface [" + serviceInterface + "] with bean name [" + serviceBeanName + "], existing definition [ " + existingDefinition + "], new definition [" + serviceBeanDefinition + "]"; logger.error(CONFIG_DUPLICATED_BEAN_DEFINITION, "", "", msg); throw new BeanDefinitionStoreException( serviceBeanDefinition.getResourceDescription(), serviceBeanName, msg); } registry.registerBeanDefinition(serviceBeanName, serviceBeanDefinition); if (logger.isInfoEnabled()) { logger.info("Register ServiceBean[" + serviceBeanName + "]: " + serviceBeanDefinition); } } @Override public void setEnvironment(Environment environment) { this.environment = environment; } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.servicePackagesHolder = applicationContext.getBean(ServicePackagesHolder.BEAN_NAME, ServicePackagesHolder.class); } private class ScanExcludeFilter implements TypeFilter { private int excludedCount; @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { String className = metadataReader.getClassMetadata().getClassName(); boolean excluded = servicePackagesHolder.isClassScanned(className); if (excluded) { excludedCount++; } return excluded; } public int getExcludedCount() { return excludedCount; } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/config/ConfigurableSourceBeanMetadataElement.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/config/ConfigurableSourceBeanMetadataElement.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.beans.factory.config; import org.springframework.beans.BeanMetadataAttributeAccessor; import org.springframework.beans.BeanMetadataElement; /** * Configurable the {@link BeanMetadataAttributeAccessor#setSource(Object) source} for {@link BeanMetadataElement} * * @since 2.7.5 */ public interface ConfigurableSourceBeanMetadataElement { /** * Set the source into the specified {@link BeanMetadataElement} * * @param beanMetadataElement {@link BeanMetadataElement} instance */ default void setSource(BeanMetadataElement beanMetadataElement) { if (beanMetadataElement instanceof BeanMetadataAttributeAccessor) { ((BeanMetadataAttributeAccessor) beanMetadataElement).setSource(this); } } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/config/DubboConfigDefaultPropertyValueBeanPostProcessor.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/config/DubboConfigDefaultPropertyValueBeanPostProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.beans.factory.config; import org.apache.dubbo.config.AbstractConfig; import org.apache.dubbo.config.Constants; import org.apache.dubbo.config.spring.util.GenericBeanPostProcessorAdapter; import org.apache.dubbo.config.spring.util.ObjectUtils; import javax.annotation.PostConstruct; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.Arrays; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor; import org.springframework.core.Ordered; import org.springframework.core.PriorityOrdered; import static org.springframework.aop.support.AopUtils.getTargetClass; import static org.springframework.beans.BeanUtils.getPropertyDescriptor; import static org.springframework.util.ReflectionUtils.invokeMethod; /** * The {@link BeanPostProcessor} class for the default property value of {@link AbstractConfig Dubbo's Config Beans} * * @since 2.7.6 */ public class DubboConfigDefaultPropertyValueBeanPostProcessor extends GenericBeanPostProcessorAdapter<AbstractConfig> implements MergedBeanDefinitionPostProcessor, PriorityOrdered { /** * The bean name of {@link DubboConfigDefaultPropertyValueBeanPostProcessor} */ public static final String BEAN_NAME = "dubboConfigDefaultPropertyValueBeanPostProcessor"; @Override protected void processBeforeInitialization(AbstractConfig dubboConfigBean, String beanName) throws BeansException { // ignore auto generate bean name if (!beanName.contains("#")) { // [Feature] https://github.com/apache/dubbo/issues/5721 setPropertyIfAbsent(dubboConfigBean, Constants.ID, beanName); // beanName should not be used as config name, fix https://github.com/apache/dubbo/pull/7624 // setPropertyIfAbsent(dubboConfigBean, "name", beanName); } } @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { // DO NOTHING } protected void setPropertyIfAbsent(Object bean, String propertyName, String beanName) { Class<?> beanClass = getTargetClass(bean); PropertyDescriptor propertyDescriptor = getPropertyDescriptor(beanClass, propertyName); if (propertyDescriptor != null) { // the property is present Method getterMethod = propertyDescriptor.getReadMethod(); if (getterMethod == null) { // if The getter method is absent return; } Object propertyValue = invokeMethod(getterMethod, bean); if (propertyValue != null) { // If The return value of "getId" method is not null return; } Method setterMethod = propertyDescriptor.getWriteMethod(); if (setterMethod != null) { // the getter and setter methods are present if (Arrays.equals( ObjectUtils.of(String.class), setterMethod.getParameterTypes())) { // the param type is String // set bean name to the value of the property invokeMethod(setterMethod, bean, beanName); } } } } /** * @return Higher than {@link InitDestroyAnnotationBeanPostProcessor#getOrder()} * @see InitDestroyAnnotationBeanPostProcessor * @see CommonAnnotationBeanPostProcessor * @see PostConstruct */ @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE + 1; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjector.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjector.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.extension; import org.apache.dubbo.common.extension.ExtensionAccessor; import org.apache.dubbo.common.extension.ExtensionInjector; import org.apache.dubbo.common.extension.SPI; import org.apache.dubbo.common.utils.StringUtils; import java.util.Arrays; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.context.ApplicationContext; public class SpringExtensionInjector implements ExtensionInjector { private ApplicationContext context; @Deprecated public static void addApplicationContext(final ApplicationContext context) {} public static SpringExtensionInjector get(final ExtensionAccessor extensionAccessor) { return (SpringExtensionInjector) extensionAccessor.getExtension(ExtensionInjector.class, "spring"); } public ApplicationContext getContext() { return context; } public void init(final ApplicationContext context) { this.context = context; } @Override @SuppressWarnings("unchecked") public <T> T getInstance(Class<T> type, String name) { if (context == null) { // ignore if spring context is not bound return null; } // check @SPI annotation if (type.isInterface() && type.isAnnotationPresent(SPI.class)) { return null; } T bean = getOptionalBean(context, name, type); if (bean != null) { return bean; } // logger.warn("No spring extension (bean) named:" + name + ", try to find an extension (bean) of type " + // type.getName()); return null; } private <T> T getOptionalBean(final ListableBeanFactory beanFactory, final String name, final Class<T> type) { if (StringUtils.isEmpty(name)) { return getOptionalBeanByType(beanFactory, type); } if (beanFactory.containsBean(name)) { return beanFactory.getBean(name, type); } return null; } private <T> T getOptionalBeanByType(final ListableBeanFactory beanFactory, final Class<T> type) { String[] beanNamesForType = beanFactory.getBeanNamesForType(type, true, false); if (beanNamesForType == null) { return null; } if (beanNamesForType.length > 1) { throw new IllegalStateException("Expect single but found " + beanNamesForType.length + " beans in spring context: " + Arrays.toString(beanNamesForType)); } return beanFactory.getBean(beanNamesForType[0], type); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceAttributes.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceAttributes.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference; /** * Attribute names of {@link org.apache.dubbo.config.annotation.DubboReference} * and {@link org.apache.dubbo.config.ReferenceConfig} */ public interface ReferenceAttributes { String ID = "id"; String INTERFACE = "interface"; String INTERFACE_NAME = "interfaceName"; String INTERFACE_CLASS = "interfaceClass"; String ACTUAL_INTERFACE = "actualInterface"; String GENERIC = "generic"; String REGISTRY = "registry"; String REGISTRIES = "registries"; String REGISTRY_IDS = "registryIds"; String GROUP = "group"; String VERSION = "version"; String ARGUMENTS = "arguments"; String METHODS = "methods"; String PARAMETERS = "parameters"; String PROVIDED_BY = "providedBy"; String PROVIDER_PORT = "providerPort"; String URL = "url"; String CLIENT = "client"; // /** // * When enable, prefer to call local service in the same JVM if it's present, default value is true // * @deprecated using scope="local" or scope="remote" instead // */ // @Deprecated String INJVM = "injvm"; String CHECK = "check"; String INIT = "init"; String LAZY = "lazy"; String STUBEVENT = "stubevent"; String RECONNECT = "reconnect"; String STICKY = "sticky"; String PROXY = "proxy"; String STUB = "stub"; String CLUSTER = "cluster"; String CONNECTIONS = "connections"; String CALLBACKS = "callbacks"; String ONCONNECT = "onconnect"; String ONDISCONNECT = "ondisconnect"; String OWNER = "owner"; String LAYER = "layer"; String RETRIES = "retries"; String LOAD_BALANCE = "loadbalance"; String ASYNC = "async"; String ACTIVES = "actives"; String SENT = "sent"; String MOCK = "mock"; String VALIDATION = "validation"; String TIMEOUT = "timeout"; String CACHE = "cache"; String FILTER = "filter"; String LISTENER = "listener"; String APPLICATION = "application"; String MODULE = "module"; String CONSUMER = "consumer"; String MONITOR = "monitor"; String PROTOCOL = "protocol"; String TAG = "tag"; String MERGER = "merger"; String SERVICES = "services"; String SCOPE = "scope"; }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanSupport.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanSupport.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.ProvidedBy; import org.apache.dubbo.config.spring.Constants; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.util.AnnotationUtils; import org.apache.dubbo.config.spring.util.DubboAnnotationUtils; import org.apache.dubbo.rpc.service.GenericService; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.config.TypedStringValue; import org.springframework.beans.factory.support.AbstractBeanFactory; import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.ManagedMap; import org.springframework.context.ApplicationContext; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.util.ObjectUtils; import static org.apache.dubbo.common.utils.StringUtils.join; public class ReferenceBeanSupport { private static final List<String> IGNORED_ATTRS = Arrays.asList( ReferenceAttributes.ID, ReferenceAttributes.GROUP, ReferenceAttributes.VERSION, ReferenceAttributes.INTERFACE, ReferenceAttributes.INTERFACE_NAME, ReferenceAttributes.INTERFACE_CLASS); public static void convertReferenceProps(Map<String, Object> attributes, Class defaultInterfaceClass) { // interface class String interfaceName = (String) attributes.get(ReferenceAttributes.INTERFACE); if (interfaceName == null) { interfaceName = (String) attributes.get(ReferenceAttributes.INTERFACE_NAME); } if (interfaceName == null) { Object interfaceClassValue = attributes.get(ReferenceAttributes.INTERFACE_CLASS); if (interfaceClassValue instanceof Class) { interfaceName = ((Class<?>) interfaceClassValue).getName(); } else if (interfaceClassValue instanceof String) { if (interfaceClassValue.equals("void")) { attributes.remove(ReferenceAttributes.INTERFACE_CLASS); } else { interfaceName = (String) interfaceClassValue; } } } if (interfaceName == null && defaultInterfaceClass != GenericService.class) { interfaceName = defaultInterfaceClass.getName(); } Assert.notEmptyString(interfaceName, "The interface class or name of reference was not found"); ProvidedBy providedbBy = null; if (defaultInterfaceClass != null) { providedbBy = (ProvidedBy) defaultInterfaceClass.getAnnotation(ProvidedBy.class); } if (providedbBy != null && providedbBy.name() != null && providedbBy.name().length > 0) { int providedByReferenceLength = providedbBy.name().length; Object providedByServices = attributes.get(ReferenceAttributes.PROVIDED_BY); int providedByInterfaceLength = 0; String[] providedByInterfaceServices = null; if (providedByServices != null) { providedByInterfaceLength = ((String[]) providedByServices).length; providedByInterfaceServices = (String[]) providedByServices; } String[] providedbByServices = new String[providedByReferenceLength + providedByInterfaceLength]; System.arraycopy(providedbBy.name(), 0, providedbByServices, 0, providedByReferenceLength); if (providedByInterfaceLength > 0) { System.arraycopy( providedByInterfaceServices, 0, providedbByServices, providedByReferenceLength, providedByInterfaceLength); } attributes.put(ReferenceAttributes.PROVIDED_BY, providedbByServices); } attributes.put(ReferenceAttributes.INTERFACE, interfaceName); attributes.remove(ReferenceAttributes.INTERFACE_NAME); attributes.remove(ReferenceAttributes.INTERFACE_CLASS); // reset generic value String generic = String.valueOf(defaultInterfaceClass == GenericService.class); String oldGeneric = attributes.containsValue(ReferenceAttributes.GENERIC) ? String.valueOf(attributes.get(ReferenceAttributes.GENERIC)) : "false"; if (!StringUtils.isEquals(oldGeneric, generic)) { attributes.put(ReferenceAttributes.GENERIC, generic); } // Specially convert @DubboReference attribute name/value to ReferenceConfig property // String[] registry => String registryIds String[] registryIds = (String[]) attributes.get(ReferenceAttributes.REGISTRY); if (registryIds != null) { String value = join(registryIds, ","); attributes.remove(ReferenceAttributes.REGISTRY); attributes.put(ReferenceAttributes.REGISTRY_IDS, value); } } public static String generateReferenceKey(Map<String, Object> attributes, ApplicationContext applicationContext) { String interfaceClass = (String) attributes.get(ReferenceAttributes.INTERFACE); Assert.notEmptyString(interfaceClass, "No interface class or name found from attributes"); String group = (String) attributes.get(ReferenceAttributes.GROUP); String version = (String) attributes.get(ReferenceAttributes.VERSION); // ReferenceBean:group/interface:version StringBuilder beanNameBuilder = new StringBuilder("ReferenceBean:"); if (StringUtils.isNotEmpty(group)) { beanNameBuilder.append(group).append('/'); } beanNameBuilder.append(interfaceClass); if (StringUtils.isNotEmpty(version)) { beanNameBuilder.append(':').append(version); } // append attributes beanNameBuilder.append('('); // sort attributes keys List<String> sortedAttrKeys = new ArrayList<>(attributes.keySet()); Collections.sort(sortedAttrKeys); for (String key : sortedAttrKeys) { if (IGNORED_ATTRS.contains(key)) { continue; } Object value = attributes.get(key); value = convertToString(key, value); beanNameBuilder.append(key).append('=').append(value).append(','); } // replace the latest "," to be ")" if (beanNameBuilder.charAt(beanNameBuilder.length() - 1) == ',') { beanNameBuilder.setCharAt(beanNameBuilder.length() - 1, ')'); } else { beanNameBuilder.append(')'); } String referenceKey = beanNameBuilder.toString(); if (applicationContext != null) { // resolve placeholder with Spring Environment referenceKey = applicationContext.getEnvironment().resolvePlaceholders(referenceKey); // resolve placeholder with Spring BeanFactory ( using // PropertyResourceConfigurer/PropertySourcesPlaceholderConfigurer ) referenceKey = ((AbstractBeanFactory) applicationContext.getAutowireCapableBeanFactory()) .resolveEmbeddedValue(referenceKey); } return referenceKey; } private static String convertToString(String key, Object obj) { if (obj == null) { return null; } if (ReferenceAttributes.PARAMETERS.equals(key) && obj instanceof String[]) { // convert parameters array pairs to map obj = DubboAnnotationUtils.convertParameters((String[]) obj); } // to string if (obj instanceof Annotation) { AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes((Annotation) obj, true); for (Map.Entry<String, Object> entry : attributes.entrySet()) { entry.setValue(convertToString(entry.getKey(), entry.getValue())); } return String.valueOf(attributes); } else if (obj.getClass().isArray()) { Object[] array = ObjectUtils.toObjectArray(obj); String[] newArray = new String[array.length]; for (int i = 0; i < array.length; i++) { newArray[i] = convertToString(null, array[i]); } Arrays.sort(newArray); return Arrays.toString(newArray); } else if (obj instanceof Map) { Map<String, Object> map = (Map<String, Object>) obj; TreeMap newMap = new TreeMap(); for (Map.Entry<String, Object> entry : map.entrySet()) { newMap.put(entry.getKey(), convertToString(entry.getKey(), entry.getValue())); } return String.valueOf(newMap); } else { return String.valueOf(obj); } } /** * Convert to raw props, without parsing nested config objects */ public static Map<String, Object> convertPropertyValues(MutablePropertyValues propertyValues) { Map<String, Object> referenceProps = new LinkedHashMap<>(); for (PropertyValue propertyValue : propertyValues.getPropertyValueList()) { String propertyName = propertyValue.getName(); Object value = propertyValue.getValue(); if (ReferenceAttributes.METHODS.equals(propertyName) || ReferenceAttributes.ARGUMENTS.equals(propertyName)) { ManagedList managedList = (ManagedList) value; List<Map<String, Object>> elementList = new ArrayList<>(); for (Object el : managedList) { Map<String, Object> element = convertPropertyValues( ((BeanDefinitionHolder) el).getBeanDefinition().getPropertyValues()); element.remove(ReferenceAttributes.ID); elementList.add(element); } value = elementList.toArray(new Object[0]); } else if (ReferenceAttributes.PARAMETERS.equals(propertyName)) { value = createParameterMap((ManagedMap) value); } // convert ref if (value instanceof RuntimeBeanReference) { RuntimeBeanReference beanReference = (RuntimeBeanReference) value; value = beanReference.getBeanName(); } if (value == null || (value instanceof String && StringUtils.isBlank((String) value))) { // ignore null or blank string continue; } referenceProps.put(propertyName, value); } return referenceProps; } private static Map<String, String> createParameterMap(ManagedMap managedMap) { Map<String, String> map = new LinkedHashMap<>(); Set<Map.Entry<String, TypedStringValue>> entrySet = managedMap.entrySet(); for (Map.Entry<String, TypedStringValue> entry : entrySet) { map.put(entry.getKey(), entry.getValue().getValue()); } return map; } public static String generateReferenceKey(ReferenceBean referenceBean, ApplicationContext applicationContext) { return generateReferenceKey(getReferenceAttributes(referenceBean), applicationContext); } public static String generateReferenceKey(BeanDefinition beanDefinition, ApplicationContext applicationContext) { return generateReferenceKey(getReferenceAttributes(beanDefinition), applicationContext); } public static Map<String, Object> getReferenceAttributes(ReferenceBean referenceBean) { Map<String, Object> referenceProps = referenceBean.getReferenceProps(); if (referenceProps == null) { MutablePropertyValues propertyValues = referenceBean.getPropertyValues(); if (propertyValues == null) { throw new RuntimeException( "ReferenceBean is invalid, 'referenceProps' and 'propertyValues' cannot both be empty."); } referenceProps = convertPropertyValues(propertyValues); } return referenceProps; } public static Map<String, Object> getReferenceAttributes(BeanDefinition beanDefinition) { Map<String, Object> referenceProps = null; if (beanDefinition.hasAttribute(Constants.REFERENCE_PROPS)) { referenceProps = (Map<String, Object>) beanDefinition.getAttribute(Constants.REFERENCE_PROPS); } else { referenceProps = convertPropertyValues(beanDefinition.getPropertyValues()); } return referenceProps; } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false
apache/dubbo
https://github.com/apache/dubbo/blob/ac1621f9a0470054c0308c47f84c7668f6bc2868/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanManager.java
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/reference/ReferenceBeanManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.spring.reference; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.common.utils.ConcurrentHashMapUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.config.spring.util.DubboBeanUtils; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER; public class ReferenceBeanManager implements ApplicationContextAware { public static final String BEAN_NAME = "dubboReferenceBeanManager"; private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass()); // reference key -> reference bean names private ConcurrentMap<String, CopyOnWriteArrayList<String>> referenceKeyMap = new ConcurrentHashMap<>(); // reference alias -> reference bean name private ConcurrentMap<String, String> referenceAliasMap = new ConcurrentHashMap<>(); // reference bean name -> ReferenceBean private ConcurrentMap<String, ReferenceBean> referenceBeanMap = new ConcurrentHashMap<>(); // reference key -> ReferenceConfig instance private ConcurrentMap<String, ReferenceConfig> referenceConfigMap = new ConcurrentHashMap<>(); private ApplicationContext applicationContext; private volatile boolean initialized = false; private ModuleModel moduleModel; public void addReference(ReferenceBean referenceBean) throws Exception { String referenceBeanName = referenceBean.getId(); Assert.notEmptyString(referenceBeanName, "The id of ReferenceBean cannot be empty"); if (!initialized) { // TODO add issue url to describe early initialization logger.warn( CONFIG_DUBBO_BEAN_INITIALIZER, "", "", "Early initialize reference bean before DubboConfigBeanInitializer," + " the BeanPostProcessor has not been loaded at this time, which may cause abnormalities in some components (such as seata): " + referenceBeanName + " = " + ReferenceBeanSupport.generateReferenceKey(referenceBean, applicationContext)); } String referenceKey = getReferenceKeyByBeanName(referenceBeanName); if (StringUtils.isEmpty(referenceKey)) { referenceKey = ReferenceBeanSupport.generateReferenceKey(referenceBean, applicationContext); } ReferenceBean oldReferenceBean = referenceBeanMap.get(referenceBeanName); if (oldReferenceBean != null) { if (referenceBean != oldReferenceBean) { String oldReferenceKey = ReferenceBeanSupport.generateReferenceKey(oldReferenceBean, applicationContext); throw new IllegalStateException("Found duplicated ReferenceBean with id: " + referenceBeanName + ", old: " + oldReferenceKey + ", new: " + referenceKey); } return; } referenceBeanMap.put(referenceBeanName, referenceBean); // save cache, map reference key to referenceBeanName this.registerReferenceKeyAndBeanName(referenceKey, referenceBeanName); // if add reference after prepareReferenceBeans(), should init it immediately. if (initialized) { initReferenceBean(referenceBean); } } private String getReferenceKeyByBeanName(String referenceBeanName) { Set<Map.Entry<String, CopyOnWriteArrayList<String>>> entries = referenceKeyMap.entrySet(); for (Map.Entry<String, CopyOnWriteArrayList<String>> entry : entries) { if (entry.getValue().contains(referenceBeanName)) { return entry.getKey(); } } return null; } public void registerReferenceKeyAndBeanName(String referenceKey, String referenceBeanNameOrAlias) { CopyOnWriteArrayList<String> list = ConcurrentHashMapUtils.computeIfAbsent( referenceKeyMap, referenceKey, (key) -> new CopyOnWriteArrayList<>()); if (list.addIfAbsent(referenceBeanNameOrAlias)) { // register bean name as alias referenceAliasMap.put(referenceBeanNameOrAlias, list.get(0)); } } public ReferenceBean getById(String referenceBeanNameOrAlias) { String referenceBeanName = transformName(referenceBeanNameOrAlias); return referenceBeanMap.get(referenceBeanName); } // convert reference name/alias to referenceBeanName private String transformName(String referenceBeanNameOrAlias) { return referenceAliasMap.getOrDefault(referenceBeanNameOrAlias, referenceBeanNameOrAlias); } public List<String> getBeanNamesByKey(String key) { return Collections.unmodifiableList(referenceKeyMap.getOrDefault(key, new CopyOnWriteArrayList<>())); } public Collection<ReferenceBean> getReferences() { return new HashSet<>(referenceBeanMap.values()); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; moduleModel = DubboBeanUtils.getModuleModel(applicationContext); } /** * Initialize all reference beans, call at Dubbo starting * * @throws Exception */ public void prepareReferenceBeans() throws Exception { initialized = true; for (ReferenceBean referenceBean : getReferences()) { initReferenceBean(referenceBean); } } /** * NOTE: This method should only call after all dubbo config beans and all property resolvers is loaded. * * @param referenceBean * @throws Exception */ public synchronized void initReferenceBean(ReferenceBean referenceBean) throws Exception { if (referenceBean.getReferenceConfig() != null) { return; } // TOTO check same unique service name but difference reference key (means difference attributes). // reference key String referenceKey = getReferenceKeyByBeanName(referenceBean.getId()); if (StringUtils.isEmpty(referenceKey)) { referenceKey = ReferenceBeanSupport.generateReferenceKey(referenceBean, applicationContext); } ReferenceConfig referenceConfig = referenceConfigMap.get(referenceKey); if (referenceConfig == null) { // create real ReferenceConfig Map<String, Object> referenceAttributes = ReferenceBeanSupport.getReferenceAttributes(referenceBean); referenceConfig = ReferenceCreator.create(referenceAttributes, applicationContext) .defaultInterfaceClass(referenceBean.getObjectType()) .build(); // set id if it is not a generated name if (referenceBean.getId() != null && !referenceBean.getId().contains("#")) { referenceConfig.setId(referenceBean.getId()); } // cache referenceConfig referenceConfigMap.put(referenceKey, referenceConfig); // register ReferenceConfig moduleModel.getConfigManager().addReference(referenceConfig); moduleModel.getDeployer().setPending(); } // associate referenceConfig to referenceBean referenceBean.setKeyAndReferenceConfig(referenceKey, referenceConfig); } }
java
Apache-2.0
ac1621f9a0470054c0308c47f84c7668f6bc2868
2026-01-04T14:45:57.057261Z
false