您的位置:首页 > 编程语言 > Java开发

【Spring】第一章 简单示例

2015-06-26 15:24 351 查看
一、spring简单demo

<context:annotation-config />
<context:component-scan base-package="util" />


1.引入jar文件

springframework-core.jar

springframework-beans.jar

springframework-context.jar

springframework-context-support.jar

2.编写配置文件:*.properties

login.username=zy
login.password=123456


3. 编写spring配置文件

<beans ...>
<bean id="propertyConfiger"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:login.properties"/>
</bean>
<bean id="loginService" class=" com.jd.mtroom.mtroom_core.service.impl.LoginServiceImpl">
<property name="username" value="${login.username}"/>
<property name="password" value="${login.password}"/><pre name="code" class="java"></bean></bean>



4. 如果要用properties中的值

需要在spring-test.xml中引入properties文件:PropertiesPlaceholderConfigurer。在其它bean中通过${key}来使用

要在具体类中使用,需要将具体类的全局变量,并添加getter(),setter()方法

package com.jd.mtroom.mtroom_core.bean;

public class Bean {
private String username;

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

}


5. 运行代码时需要加载spring.xml,并通过spring上下文创建bean。

public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-login.xml");
LoginService loginService =(LoginService) context.getBean("loginService");
loginService.login();
}

}


二、使用注解方式启动

1. 在配置文件中添加以下代码:使用注解,import是引入其它spring配置文件

<context:annotation-config />
<context:component-scan base-package="util" />
<import resource="classpath*:/spring/spring-jdbc.xml" />


2. 在类中引入代码时可以通过

@ContextConfiguration(locations = "classpath*:/spring/spring-test.xml")

public class BaseTest extends AbstractTestNGSpringContextTests {

protected static XmlTranslator xmlTool = new XmlTranslator();

@Resource
protected DataSource customerDataSource;

@Value("#{db['customer.name']}")
public String customerUserName ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: