配置弹簧项目

时间:2010-03-30 04:27:26

标签: spring

我的问题是:从基本版本开始,Spring中需要哪些必需的jar,我们如何配置Spring项目?

3 个答案:

答案 0 :(得分:5)

转到Spring home page并下载Spring(这里,我使用的是2.5.x版本)

安装完成后,将以下jar放入类路径

< SPRING_HOME> /dist/spring.jar

这里有一个单独的bean

package br.com.introducing.Hello;

public class Hello {

    private String message;

    // getter's and setter's

}

...

编写单个xml来配置bean,如下所示

// app.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="hello" class="br.com.introducing.Hello">
        <property name="message" value="What do you want ?"/>
    </bean>
</beans>

将app.xml放在root classpath

你的psvm

public static void main(String [] args) {
    ApplicationContext appContext = new ClassPathXmlApplicationContext("app.xml");

    Hello hello = (Hello) appContext.getBean("hello");

    hello.getMessage(); // outputs What do you want ?
}

<强>更新

  

applicationContext.xml的作用是什么

使用getBean方法时,它的行为类似于Factory模式。像

这样的东西
public class ApplicationContext {

    Map wiredBeans = new HashMap();

    public static Object getBean(String beanName) {
        return wiredBeans.get(beanName);
    }

}

如Spring in Action书中所述

  

它是一个通用工厂,创造和调整许多类型的豆。

但是,还有更多

  • 允许您加载文件
  • 您可以发布活动
  • 支持i18n(i18n代表国际化)

假设这里是messages.properties(类路径的根)

// messages.properties

messsageCode=What do you want ?

要启用i18n,您必须定义一个名为 messageSource 的bean以利用我们的资源,如下所示

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="messages"/>
    </bean>
</beans>

现在,您可以使用它

appContext.getMessage("messsageCode", null, null); // outputs What do you want ?

通常,我们不需要在xml文件中定义所有bean。您可以使用注释(启用组件扫描所需的其他设置)而不是xml,类似

package br.com.introducing.Hello;

@Component
public class Hello {

    private String message;

    // getter's and setter's

}

组件注释说:

  

Spring,我是一个可以通过应用程序上下文检索的通用bean

关于Spring的一个很好的资源是Spring in Action book或Spring documentation

建议:仔细阅读

答案 1 :(得分:1)

您可以查看春季understanding the webapplicationcontexts and other xml config files上的文章

认为这可以帮助您轻松获取与基本弹簧MVC相关的配置

答案 2 :(得分:0)

您还可以使用Maven来创建和管理项目。您可以了解Maven以及如何从here

开始

Maven将创建一个目录结构,项目目录中将有一个pom.xml。您可以在此文件中提及所有依赖项。例如:对于使用spring,您可以按如下方式提及依赖项,

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>2.5.3</version>
</dependency>

如果您使用Eclipse作为IDE,则需要执行以下命令,

mvn eclipse:eclipse

这将创建一个.project文件。您现在可以将项目导入Eclipse IDE并开始编写应用程序。

对于初学者,Spring参考文档和Spring in Action和Spring Recipes等书籍非常有用

相关问题