简体   繁体   English

使用Spring Bean连接数据库对象

[英]Wiring Database Object with Spring Bean

From Spring in Action book, there is an example of Spring Bean. 从“ Spring in Action”一书中可以看到一个Spring Bean的示例。 It uses Compact Disc analogy. 它使用Compact Disc类比。 When an application needs a "The Beatles" album , it creates "The Beatles" album bean , and as well as other albums. 当应用程序需要"The Beatles" album ,它将创建"The Beatles" album bean以及其他唱片集。

  1. If there are n albums in database, so should I create n album beans? 如果数据库中有n相册,那么我应该创建n相册bean吗?
  2. If it is not, how the n albums represented in application? 如果不是,如何在应用程序中代表n张专辑? Is it just a POJO domain model (not a bean)? 仅仅是POJO域模型(不是bean)吗?
  3. What is the real use case using Spring Bean? 使用Spring Bean的真正用例是什么?
  1. You just need to have one Album class and annotate it as a @Component or do it via xml. 您只需要具有一个Album类并将其注释为@Component或通过xml进行注释即可。

  2. The terms bean and POJO are interchangeable. 术语beanPOJO是可以互换的。 As per Spring in action 4rd edition , Spring tries hard to be a non-invasive framework. 根据Spring in action 4rd edition ,Spring努力成为一个非侵入性框架。

(...)the classes in a Spring-based application often have no indication that they're being used by Spring. (...)基于Spring的应用程序中的类通常没有迹象表明它们正在被Spring使用。 At worst, a class may be annotated with one of Spring's annotations, but it's otherwise a POJO 在最坏的情况下,一个类可能会用Spring的注释之一进行注释,但否则就是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. 尽管Spring在引用应用程序组件时会宽松地使用Bean和JavaBean一词,但这并不意味着Spring组件必须遵循JavaBeans规范。 A Spring component can be any type of POJO. Spring组件可以是任何类型的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 . 用例是您可以使用Spring Dependency Injection在运行时连接bean,您的应用程序可以从Spring的简单性,可测试性和松散耦合中受益。

In short, a Spring bean as you refer is just a POJO used in the context of an Spring Application. 简而言之,您所引用的Spring bean只是在Spring Application上下文中使用的POJO。 If you use the xml mapping instead of the annotation, your class will be just another regular Java class, a Plain Old Java Object. 如果您使用xml映射而不是注释,则您的类将是另一个常规Java类,即Plain Old Java Object。

If there are n albums in database, so should I create n album beans? 如果数据库中有n个相册,那么我应该创建n个相册bean吗?

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; 如果有n张专辑,那么将它们全部明确地包含在App.config文件中将非常麻烦。 but you could. 但是你可以。 You would probably add an AlbumService (@Service) @Bean and associated @Repository to handle writing and retrieving them from the DB. 您可能会添加一个AlbumService (@Service) @Bean和相关@Repository处理写作和从数据库中检索它们。

If it is not, how the n albums represented in application? 如果不是,如何在应用程序中代表n张专辑? Is it just a POJO domain model (not a bean)? 仅仅是POJO域模型(不是bean)吗?

You could have an Album @Entity bean with the attributes of an album. 您可以使用具有Album属性的Album @Entity bean。 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. 您的数据库中将包含n个相册。 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() ; 如果您想要它们,您可以做albumService.findAll() ; and get a container of them. 并得到一个容器。

What is the real use case using Spring Bean? 使用Spring Bean的真正用例是什么?

Spring is the real use case of a Spring Bean. Spring是Spring Bean的真正用例。 According to the Spring IoC Container Reference : 根据Spring IoC容器参考

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. 在Spring中,构成应用程序主干并由Spring IoC容器管理的对象称为bean。 A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Bean是由Spring IoC容器实例化,组装和以其他方式管理的对象。 Otherwise, a bean is simply one of many objects in your application. 否则,bean仅仅是应用程序中许多对象之一。 Beans, and the dependencies among them, are reflected in the configuration metadata used by a container. Bean及其之间的依赖关系反映在容器使用的配置元数据中。

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. 如果我是您,那么我将不同于光盘作为Spring bean的类比,尤其是在您以后的问题上。 Quite plainly, any Java object can be declared as a bean in Spring, whether you're using XML configuration or Java configuration. 很明显,无论您使用的是XML配置还是Java配置,任何Java对象都可以在Spring中声明为Bean。

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: 我可以通过在XML配置文件中将其声明为Spring Bean:

<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. 可以检索已配置的foo对象,并将设置其所有属性(包括bar This is the core use case of Spring, ie letting you configure how the building blocks of your application resolve their dependencies at runtime. 这是Spring的核心用例,即让您配置应用程序的构建块如何在运行时解析其依赖性。 Initially Spring was all about configuration outside of code, but the focus now has slightly changed, with things like component scans and Java configuration... 最初,Spring只是关于代码之外的配置,但是现在的重点已经稍有变化,例如组件扫描和Java配置。

Anyway, to conclude with this brief example, the following line of code will print 10: 无论如何,以这个简短的示例结束,下面的代码行将输出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. 在此示例中,我选择了Foo和Bar,但它也可能是Web服务,实现一些业务逻辑的服务,数据库,ORM外观,模板引擎,线程池等等。使用数据对象,而不是数据对象本身,尽管这是完全可能的。

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. 现在返回您的用例,在Spring应用程序中,如果我正在使用数据库编码Web应用程序,则通常将具有以下组件:控制器(Web边界),服务(用于业务逻辑),存储库(用于查询),当然还有数据源。 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: 请注意,使用此配置,没有特定的数据提供程序被编译到我的Java代码中,而是保留在配置中:

<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. 光盘不会被描述为Spring Bean,但肯定是实际Spring Bean的参数和返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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