Spring IOC快速入门
Spring IOC底层实现原理
Spring官方下载地址:
https://repo.spring.io/libs-release-local/org/springframework/spring/
目录结构:
docs:api文档和开发规范 libs:开发需要的jar包和源码 schema:开发需要的schema文件
新建项目:
项目结构:
没有resources解决方法:
ok
项目测试:
在pom.xml中导入依赖文件
copy代码:
<dependencies>
<dependency>
<groupId>junit
</groupId
>
<artifactId>junit
</artifactId
>
<version>4.12</version
>
<scope>test
</scope
>
</dependency
>
<dependency>
<groupId>org
.springframework
</groupId
>
<artifactId>spring
-core
</artifactId
>
<version>4.2.4.RELEASE
</version
>
</dependency
>
<dependency>
<groupId>org
.springframework
</groupId
>
<artifactId>spring
-context
</artifactId
>
<version>4.2.4.RELEASE
</version
>
</dependency
>
<dependency>
<groupId>org
.springframework
</groupId
>
<artifactId>spring
-beans
</artifactId
>
<version>4.2.4.RELEASE
</version
>
</dependency
>
<dependency>
<groupId>org
.springframework
</groupId
>
<artifactId>spring
-expression
</artifactId
>
<version>4.2.4.RELEASE
</version
>
</dependency
>
<dependency>
<groupId>log4j
</groupId
>
<artifactId>log4j
</artifactId
>
<version>1.2.17</version
>
</dependency
>
<dependency>
<groupId>org
.junit
.jupiter
</groupId
>
<artifactId>junit
-jupiter
</artifactId
>
<version>RELEASE
</version
>
<scope>compile
</scope
>
</dependency
>
</dependencies
>
新建Java文件
Java文件变成源代码文件
右键java文件
测试传统开发方式和Spring反转控制和依赖注入
在resources下新建xml配置文件
copy代码:
<?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">
<!--UserService的创建权交给了Spring
-->
<bean id
="userService" class="com.imooc.ioc.demo1.UserServiceImpl">
<!--设置属性
-->
<property name
="name" value
="食品名称"/>
<property name
="taste" value
="食品口味"/>
<property name
="kind" value
="食品种类"/>
</bean
>
</beans
>
1.新建包
2.新建接口UserService
public interface UserService {
public void sayHello();
}
3.新建类UserServiceImpl
public class UserServiceImpl implements UserService {
private String name
;
private String taste
;
private String kind
;
public void sayHello(){
System
.out
.println("hello spring");
System
.out
.println(name
+kind
+taste
);
}
public String
getName() {
return name
;
}
public void setName(String name
) {
this.name
= name
;
}
public String
getTaste() {
return taste
;
}
public void setTaste(String taste
) {
this.taste
= taste
;
}
public String
getKind() {
return kind
;
}
public void setKind(String kind
) {
this.kind
= kind
;
}
}
4.新建测试类SpringDemo1
public class SpringDemo1 {
@Test
public void demo1(){
UserServiceImpl userService
= new UserServiceImpl();
userService
.setName("张三");
userService
.sayHello();
}
@Test
public void demo2(){
ApplicationContext applicationContext
= new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService
=(UserService
) applicationContext
.getBean("userService");
userService
.sayHello();
}
}