题
我的问题是:从基础来看,Spring 中应该需要哪些必要的 jar 以及我们如何配置 Spring 项目?
解决方案
去春天 主页 并下载Spring(这里我使用的是2.5.x版本)
安装后,将以下jar放入类路径中
<SPRING_HOME>/dist/spring.jar
这是一颗豆子
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 放入根类路径中
还有你的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 方法时,它的行为类似于工厂模式。就像是
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,您必须定义一个名为的 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》一书或 Spring文档
建议:仔细读
其他提示
您可以看看文章在了解webapplicationcontexts和其他XML配置文件在弹簧
认为这是可以帮助您获得相关的基础Spring MVC的轻松的配置
您也可以使用Maven来创建和管理项目。您可以获取有关Maven和如何的想法从启动此处
一个目录结构将Maven的创建,将有你的项目目录内的pom.xml。那么你可以说在这个文件中的所有依存关系。例如:使用弹簧,可以提及的依赖性如下,
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>2.5.3</version>
</dependency>
如果使用的是Eclipse作为IDE,需要执行以下命令,
mvn eclipse:eclipse
这将创建一个.project文件。现在,您可以将项目导入Eclipse IDE和开始编写你的应用程序。
对于初学者来说,弹簧参考文档和书籍如Spring在行动和春季食谱是非常有用的