【Spring】第一章 简单示例

一、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 ;
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值