spring boot ioc - downgoon/hello-world GitHub Wiki
最简单的 spring-boot 只需要 一个 pom.xml 和 一行代码
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
代码:
SpringApplication.run(Application.class, args);
$ git checkout spring-boot
$ git checkout spring-boot-c1-ioc
谈到 spring ,最基础的功能就是 Bean 声明周期的管理。 spring-boot 把这些弄得非常简单,“零配置”了:
-
以spring-boot 方式启动:
SpringApplication.run(Application.class, args);
- 用Annotation声明一个Bean:比如本文用 @Component 声明一个对象,并交给容器管理。当然我们也可以用@Service, @Controller 或 @Repository 这些更细化的 @Component 。
-
默认读取
application.properties
配置:配置文件都不用在代码中指定了,默认就是读application.properties
。体现了**“约定俗成优于配置”**的思想。
有个SomeComponent.java
,它需要从application.properties
读取配置。它有个方法叫 sayHello
,我们希望用 spring-boot 来运行整个程序。
- 启动程序
Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
ApplicationContext context = SpringApplication.run(Application.class, args);
SomeComponent component = context.getBean(SomeComponent.class);
component.sayHello("wangyi");
component.sayHello();
}
}
- 组件
SomeComponent.java
@Component
public class SomeComponent {
@Autowired
private Environment env;
public void sayHello(String name) {
System.out.println("hello, " + name);
}
public void sayHello() {
System.out.println("hello, " + env.getProperty("hello.name"));
}
}
这个组件会读取 application.properties
的配置,spring建议通过 Environment
来获取配置中的内容。
- 配置
application.properties
hello.name=zhangsan
刚才的例子只是演示了 Spring-boot 管理 Bean 的创建和销毁,并没有演示依赖关系管理。现在 SomeComponent
依赖于 SomeDependency
提供一个姓名。
$ git checkout spring-boot
$ git checkout spring-boot-c2-dependency
@Component
public class SomeComponent {
@Autowired
private Environment env;
public void sayHello(String name) {
System.out.println("hello, " + name);
}
@Autowired
private SomeDependency sdency;
public void sayHello() {
System.out.println("hello, " + env.getProperty("hello.name") + " and " + sdency.getName());
}
}
在 SomeComponent.java
中通过
@Autowired private SomeDependency sdency;
注入依赖关系。同时在 SomeDependency
中用 @Component
创建Bean,并托管到Spring。
@Component
public class SomeDependency {
public String getName() {
return "lisi";
}
}