ps : 只是单纯的打了一遍 /
javaEE颠覆者第一章
1.3.1 依赖注入
我是直接用maven来创建项目的
关于maven的安装 这里就不在多加描述了
直接开始吧
这是pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wisely</groupId>
<artifactId>spring4</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-comipler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
(1)编写功能类的bean
package spring4.main;
import org.springframework.stereotype.Service;
@Service//声明一个spring管理bean
public class FunctionService {
public String sayHello(String word) {
return "hello "+word+"!";
}
}
(2)使用功能类的bean
package spring4.main;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserFunctionService {
@Autowired//注入bean 等价于 Inject Resource
FunctionService functionService;
public String sayHello(String word) {
return functionService.sayHello(word);
}
}
(3)配置类
package spring4.main;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration //配置类声明
@ComponentScan("spring4.main")//扫描包名下所有的带有 @Service @Componet @Repository @Controller注解的类,自动注册为bean
public class DiConfig {
}
(4)运行
package spring4.main;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context
= new AnnotationConfigApplicationContext(DiConfig.class);//使用AnnotationConfigApplicationContext 作为Spring容器 接受一个配置类作为参数
UserFunctionService userFunctionService
=context.getBean(UserFunctionService.class);
System.out.println(userFunctionService.sayHello("helloword"));//获取声明的bean
context.close();
}
}
结果