導入jar包
- 4+1:4個核心+1個依賴
- Beans:spring-beans-5.2.3.RELEASE.jar
- Core:spring-core-5.2.3.RELEASE.jar
- Context:spring-context-5.2.3.RELEASE.jar
- SpEL:spring-expression-5.2.3.RELEASE.jar
- commons-loggins:commons-longging-1.2.jar
- .jar、sources.jar及javadoc.jar區別
- .jar是開發所需要的字節碼jar包;
- sources.jar是源碼jar包;
- javadoc.jar是api開發文檔jar包。
項目目錄
項目代碼
配置文件xml
常用名稱:applicationContext.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.xsd">
<!-- 配置bean -->
<bean id="UserService" class="com.zhangzibu.spring.ioc.service.impl.UserServiceImpl"></bean>
</beans>
-
<bean>:配置需要創建的對象
-
id:用於之後從Spring容器獲得實例時使用的
-
class:需要創建實例的全限定類名
-
Java代碼
接口
package com.zhangzibu.spring.ioc.service;
public interface UserService {
void hello(String para);
}
實現類
package com.zhangzibu.spring.ioc.service.impl;
import com.zhangzibu.spring.ioc.service.UserService;
public class UserServiceImpl implements UserService {
@Override
public void hello(String para) {
System.out.println("Hello " + para);
}
}
測試類
package com.zhangzibu.spring;
import com.zhangzibu.spring.ioc.service.UserService;
import com.zhangzibu.spring.ioc.service.impl.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
@Test
public void testIoc(){
// 之前開發
UserService userServiceNew = new UserServiceImpl();
userServiceNew.hello("new 張子布");
// 從Spring容器中獲得
// 1.獲得容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/applicationContext.xml");
// 2.獲得實例對象
UserService userServiceIoc = (UserService) applicationContext.getBean("UserService");
userServiceIoc.hello("IOC 張子布");
}
}
結果
Hello new 張子布
Hello IOC 張子布