Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to define a Spring Bean CLASS with NO Interface

I have a spring bean that extends HibernateDaoSupport. I want this bean injected into my Controllers, but I do NOT want it to implement any interface. I just want to refer to the concrete class from within the rest of my code (not use the AopProxy perhaps?) Does anyone have a way of doing this?

<bean id="mySampleService" class="com.sample.MySampleService">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

@Autowired
private MySampleService mySampleService;

... getters and setters ....

I know it's a good idea to use the interface and that's the whole point of IoC, but PLEASE DON'T suggest I use the interface.

like image 784
fandang Avatar asked Jul 17 '12 17:07

fandang


People also ask

How to define spring beans in XML config?

Spring beans definition in xml config. 2.1. Single configuration file with bean definitions. You can define all spring beans and their transitive dependencies in single xml file. This xml file can be used to create application context. beans.xml.

What is a bean in Spring Boot?

A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Here we are going to discuss how to create a Spring Bean in 3 different ways as follows: Creating Bean Inside an XML Configuration File (beans.xml)

How to define a bean in Java without XML?

We can even define beans using Java code and the configuration class we made earlier without the need for XML. For this, we will create a new implementation of the Teacher interface named DrawingTeacher.java and we will also have a QuoteService implementation that we will inject using Java code.

What is spring bean in Java?

How to Create a Spring Bean in 3 Different Ways? Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects.


1 Answers

If class to be proxied (by transactional proxy in your case) implements any interface (InitializingBean implemented by HibernateDaoSupport in your case), Spring by default uses proxying strategy based on JDK dynamic proxies.

So, it creates a proxy of type InitializingBean, that, obviously, cannot be injected into a field of type MySampleService.

If you don't want to use interface you can override the strategy used by transactional aspect by declaring <tx:annotation-driven> with proxy-target-class = "true".

See also:

  • 7.6 Proxying mechanisms
like image 106
axtavt Avatar answered Oct 19 '22 11:10

axtavt