spring boot 借助于其强大的注解功能,帮助我们快速实现。这里简单介绍一下有关IOC的几个注解。
FunctionService类:(业务类)
package bw.swn.boot.service;
import org.springframework.stereotype.Service;
@Service
public class FunctionService {
public String sayHello(String name) {
return "Hello "+name+" !";
}
}
UseFunctionService类:(调用类)
package bw.swn.boot.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class UseFunctionService {
@Autowired
private FunctionService functionService;
public void show(String name) {
System.out.println(this.functionService.sayHello(name));
}
}
IocConfig类(完成装配)
package bw.swn.boot.service;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("bw.swn.boot.service")
public class IocConfig {
}
启动类:
package bw.swn.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import bw.swn.boot.service.IocConfig;
import bw.swn.boot.service.UseFunctionService;
@SpringBootApplication
public class SpringIocApplication {
public static void main(String[] args) {
SpringApplication.run(SpringIocApplication.class, args);
AnnotationConfigApplicationContext ctx=
new AnnotationConfigApplicationContext(IocConfig.class);
UseFunctionService use=ctx.getBean(UseFunctionService.class);
use.show("spring boot");
ctx.close();
}
}
输出结果: