- Spring — Create bean in XML with reference to Java bean, and the other way around
- 3 Answers 3
- XML Defined Beans in Spring Boot
- Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
- 1. Introduction
- 2. The @ImportResource Annotation
- 3. Accessing Properties in XML Configurations
- 4. Recommended Approach
- 5. Conclusion
Spring — Create bean in XML with reference to Java bean, and the other way around
If I have a bean created in Java, with @Bean, how do I reference this bean in XML when creating a bean there? And if I have a bean created in XML, how do I reference this bean in Java when creating a bean there?
3 Answers 3
Creating a bean in Java class is equivalent to creating the bean in the XML file. So if you want to refer a bean created in Java class in an XML file, simply use ref= beanName attribute to refer the bean and vice versa.
In the official documentation it says:
4.2.1. Declaring a bean
To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory. By default, the bean name will be that of the method name.
@Configuration public class AppConfig < @Bean public TransferService transferService() < return new TransferServiceImpl(); >>
The above is exactly equivalent to the following appConfig.xml:
Both will result in a bean named transferService being available in the BeanFactory/ApplicationContext, bound to an object instance of type TransferServiceImpl:
And also you need to make sure you add
in your xml so your XML configuration and Java configuration has same bean definitions if they are declared in different contexts.
And if you want to include your traditional bean configuration from XML to Java configuration, then you need to Import the XML resource to that class as below:
Also if you would like to read more about this I would suggest you to have a look at the official documentation: docs.spring.io/spring-javaconfig/docs/1.0.0.m3/reference/html/…
Thanks! Could you elaborate on the last Bean, the ConfigurationPostProcessor. What does it do, and why do I always need it when beans are declared both in Java and XML?
It is added to pick up all the beans declared in Java configuration from an XML file so as Spring container can pick and register those beans. However, you can also add
bean declaration in java and using them in XML: you need
Other answers only answer part of the picture. Let me try to summarize the big picture. The key point is that every bean has an identifier which is unique within the spring container. We can use this identifier to reference a bean.
The bean identifier can be configured by :
- XML : id and name attribute in the
- Java Config :
- value and name attribute in @Bean .
- value attribute in @Component and its stereotype annotation such as @Service , @Controller etc.
If the identifier is not configured explicitly , depending on how the beans are declared , a default one will be generated for them:
- For beans declared using XML, @Component and its stereotype , it is the class name of that bean formatted in lowerCamelCase.
- For beans declared using @Bean , it is the name of that bean method
To reference a bean declared in Java configuration in XML , use ref property to refer to its identifier such as :
So service property is reference to a bean which the identifier is called bar
To reference a bean declared in XML in Java , you can simply annotate @Autowired on a field. If there is only one spring bean which the type is the same as the type of this field (i.e. Bar in this case) , this bean will automatically be referenced and injected . It is called auto-wired by type which you does not require to reference it by the bean identifier :
On the other hand , if there are multiple beans which the type are also Bar, you have to use @Qualifier with the bean identifier to reference a particular bean among these Bar beans. This is called auto-wired by name :
XML Defined Beans in Spring Boot
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Introduction
Before Spring 3.0, XML was the only way to define and configure beans. Spring 3.0 introduced JavaConfig, allowing us to configure beans using Java classes. However, XML configuration files are still used today.
In this tutorial, we’ll discuss how to integrate XML configurations into Spring Boot.
2. The @ImportResource Annotation
The @ImportResource annotation allows us to import one or more resources containing bean definitions.
Let’s say we have a beans.xml file with the definition of a bean:
To use it in a Spring Boot application, we can use the @ImportResource annotation, telling it where to find the configuration file:
@Configuration @ImportResource("classpath:beans.xml") public class SpringBootXmlApplication implements CommandLineRunner < @Autowired private Pojo pojo; public static void main(String[] args) < SpringApplication.run(SpringBootXmlApplication.class, args); >>
In this case, the Pojo instance will be injected with the bean defined in beans.xml.
3. Accessing Properties in XML Configurations
What about using properties in XML configuration files? Let’s say we want to use a property declared in our application.properties file:
sample=string loaded from properties!
Let’s update the Pojo definition, in beans.xml, to include the sample property:
Next, let’s verify if the property is properly included:
@RunWith(SpringRunner.class) @SpringBootTest(classes = SpringBootXmlApplication.class) public class SpringBootXmlApplicationIntegrationTest < @Autowired private Pojo pojo; @Value("$") private String sample; @Test public void whenCallingGetter_thenPrintingProperty() < assertThat(pojo.getField()) .isNotBlank() .isEqualTo(sample); >>
Unfortunately, this test will fail because, by default, the XML configuration file can’t resolve placeholders. However, we can solve this by including the @EnableAutoConfiguration annotation:
@Configuration @EnableAutoConfiguration @ImportResource("classpath:beans.xml") public class SpringBootXmlApplication implements CommandLineRunner < // . >
This annotation enables auto-configuration and attempts to configure beans.
4. Recommended Approach
We can continue using XML configuration files. But we can also consider moving all configuration to JavaConfig for a couple of reasons. First, configuring the beans in Java is type-safe, so we’ll catch type errors at compile time. Also, XML configuration can grow quite large, making it difficult to maintain.
5. Conclusion
In this article, we saw how to use XML configuration files to define our beans in a Spring Boot application. As always, the source code of the example we used is available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: