Spring框架:String配置
String配置
<?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.xsd">
<!-- 将UserController交给Spring管理-->
<!-- id:为这个bean起一个名字,要求唯一,一般是类名的小写-->
<!-- class:类的全路径-->
<bean id="userController" class="com.sky.controller.UserController">
<!-- property:告诉Spring我是有依赖对象的-->
<!-- name:依赖对象,使用set注入方法的配置-->
<!-- ref:依赖对象的数据类型是对象时使用-->
<property name="service" ref="userService"></property>
</bean>
<!-- 将UserService交给Spring管理-->
<bean id="userService" class="com.sky.service.UserService">
<property name="mapper" ref="userMapper"></property>
</bean>
<!-- 将UserMapper交给Spring管理-->
<bean id="userMapper" class="com.sky.mapper.UserMapper">
<!-- value:依赖对象的数据类型是简单数据类型时使用-->
<property name="hell" value="sss"></property>
</bean>
</beans>
测试
package com.sky.test;
import com.sky.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
// 加载容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
// userController就是bean的id
UserController userController = (UserController) applicationContext.getBean("userController");
int login = userController.login("111111", "222222");
if (login == 1) {
System.out.println("测试OK");
} else {
System.out.println("测试ON");
}
}
}
controller
package com.sky.controller;
import com.sky.service.UserService;
public class UserController {
// 实现注入的方法:set注入
// 1:添加依赖对象的属性
private UserService service;
// 2:添加set方法
public void setService(UserService service) {
this.service = service;
}
public int login(String username, String pwd){
System.out.println("controller======界面");
System.out.println("对象类型注入:"+service);
return service.login(username,pwd);
}
}
service
package com.sky.service;
import com.sky.mapper.UserMapper;
public class UserService {
private UserMapper mapper;
public void setMapper(UserMapper mapper) {
this.mapper = mapper;
}
public int login(String username, String pwd){
System.out.println("service======界面");
System.out.println("对象类型注入:"+mapper);
return mapper.login(username,pwd);
}
}
mapper
package com.sky.mapper;
public class UserMapper {
// 注入普通简单数据类型
private String hell;
public void setHell(String hell) {
this.hell = hell;
}
public int login(String username, String pwd){
System.out.println("mapper======界面");
System.out.println("普通类型注入:"+hell);
int i = 0;
if ("111111".equals(username) && "222222".equals(pwd)) {
i = 1;
}
return i;
}
}