简体   繁体   中英

Wiring Database Object with Spring Bean

From Spring in Action book, there is an example of Spring Bean. It uses Compact Disc analogy. When an application needs a "The Beatles" album , it creates "The Beatles" album bean , and as well as other albums.

  1. If there are n albums in database, so should I create n album beans?
  2. If it is not, how the n albums represented in application? Is it just a POJO domain model (not a bean)?
  3. What is the real use case using Spring Bean?
  1. You just need to have one Album class and annotate it as a @Component or do it via xml.

  2. The terms bean and POJO are interchangeable. As per Spring in action 4rd edition , Spring tries hard to be a non-invasive framework.

(...)the classes in a Spring-based application often have no indication that they're being used by Spring. At worst, a class may be annotated with one of Spring's annotations, but it's otherwise a POJO

and

Although Spring uses the words bean and JavaBean liberally when referring to application components, this doesn't mean a Spring component must follow the JavaBeans specification to the letter. A Spring component can be any type of POJO.

  1. The use case is that you can use the Spring Dependency Injection to wire your beans on run-time, your application can benefit from Spring in terms of simplicity, testability, and loose coupling .

In short, a Spring bean as you refer is just a POJO used in the context of an Spring Application. If you use the xml mapping instead of the annotation, your class will be just another regular Java class, a Plain Old Java Object.

If there are n albums in database, so should I create n album beans?

I would think not. If there are n albums it would be very cumbersome to include them all explicitly in your App.config file if that's what you're referring to; but you could. You would probably add an AlbumService (@Service) @Bean and associated @Repository to handle writing and retrieving them from the DB.

If it is not, how the n albums represented in application? Is it just a POJO domain model (not a bean)?

You could have an Album @Entity bean with the attributes of an album. When you save an album you'd set the attributes as opposed to having individual components implementing a common interface. Your DB would have n albums in it. If you needed to retrieve just one Beatles album you could query based on the album title, for example. If you wanted them all you could do albumService.findAll() ; and get a container of them.

What is the real use case using Spring Bean?

Spring is the real use case of a Spring Bean. According to the Spring IoC Container Reference :

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.

I can't provide a better answer than what's contained in the documentation or given in this answer .

If I were you, I would depart from the analogy of the compact disc as a Spring bean, especially with respect to your later questions. Quite plainly, any Java object can be declared as a bean in Spring, whether you're using XML configuration or Java configuration.

Let's suppose I have these 2 classes:

public class Foo {

    private String s;

    private Bar bar;

    // getters & setters

}

public class Bar {

    private int i;

    // getter & setter

}

I can make the former a Spring Bean by declaring it in an XML configuration file:

<bean id="foo" class="demo.Foo">
    <property name="s" value="Hello, World!" />
    <property name="bar">
        <bean class="demo.Bar">
            <property name="i" value="10" />
        </bean>
    </property>
</bean>

Now, with these 2 lines of code:

ApplicationContext ctx = new ClassPathXmlApplicationContext("app.xml");
Foo foo = ctx.getBean(Foo.class);

The foo object that was configured can be retrieved, and all its properties including bar will be set. This is the core use case of Spring, ie letting you configure how the building blocks of your application resolve their dependencies at runtime. Initially Spring was all about configuration outside of code, but the focus now has slightly changed, with things like component scans and Java configuration...

Anyway, to conclude with this brief example, the following line of code will print 10:

System.out.println(foo.getBar().getI());

In this example, I took Foo and Bar, but it could as well be a Web Service, a service implementing some business logic, a database, an ORM facade, a template engine, a thread pool, anything... But mostly components dealing with data objects, not data objects themselves, though this is entirely possible.

Now to return with your use case, in a Spring app, I would generally have these components if I'm coding a Web app with a database: a controller (the Web boundary), a service (for business logic), a repository (for querying) and of course a data source. I won't delve into too much details here (no declarative transactions for example). Notice that with this configuration, no specific data provider is compiled into my Java code, it remains in the configuration:

<bean id="cdController" class="demo.compactdisc.CdController">
    <property name="cdService" ref="cdService" />
</bean>

<bean id="cdService" class="demo.compactdisc.CdServiceImpl">
    <property name="cdRepository" ref="cdRepository" />
</bean>

<bean id="cdRepository" class="demo.compactdisc.CdRepositoryImpl">
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/test"/>
    <property name="username" value="test"/>
    <property name="password" value="s3cr3t"/>
</bean>

With your domain, the repository would return the compact discs from the database to the service, the service to the controller and the controller to the user. Compact discs would not be described as Spring beans but would certainly be parameters and return values from the actual Spring beans.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM