目录
依赖注入或控制反转(Ioc)
1. 依赖注入
@Component @Service @Repository @Controller @Autowired @Inject @Resource
搭配@Scope注解使用:
@Scope("Singleton") 一个spring容器只有一个bean的实例,此为spring的默认配置;
@Scope("Prototype")每次新建一个bean实例
@Scope("Request") web项目中,给每一个http request新建一个bean实例;
@Scope("Session") web项目中,给每一个http session新建一个bean实例;
@Scope("GlobalSession") 这个只在portal应用中有用,给每一个global http session新建一个bean实例。
2. 配置注解
@Configuration
3. 扫描注解
@ComponentScan
4. 配置类加@Bean注解
@Bean注解在方法上,表示方法返回的是一个Bean,bean的名称是方法名;
AOP
面向切面编程注解
1. @AspectJ @Before @After @Around @Pointcut @EnableAspectJAutoProxy
值注入
@Value
1. 注入普通文字
@Value("要注入的文字")
private String normalText;
2. 注入操作系统属性
@Value("#{systemProperties['os.name']}")
private String osName;
3. 注入表达式结果
@Value("#{ T(java.lang.Math).random() * 100.0}")
private double randomNumber;
4. 注入其他bean属性
@Service
public class DemoService {
@Value("其他类的属性")
private String another;
}
@Value("#{demoService.another}")
private String fromAnother;
5. 注入文件资源
@Value("classpath:com/test.txt")
private Resource testFile;
org.springframework.core.io.Resource
6. 注入网址资源
@Value("http://www.baidu.com")
private Resource testUrl;
7. 注入配置文件
@Value("${book.name}")
private String bookName;
8. 环境变量注入
@Autowired
private Environment environment;
import org.springframework.core.env.Environment;
@Configuration
@ComponentScan("com.cn")
@PropertySource("classpath:com/cn/test/test.properties
test.properties
book.author=wangyunfei
book.name=spring boot
public void outputResource() {
System.out.println(normalName);
System.out.println(osName);
System.out.println(randomNumber);
System.out.println(fromAnother);
System.out.println(IOUtils.toString(testFile.getInputStream()));
System.out.println(IOUtils.toString(testUrl.getInputStream()));
System.out.println(bookName);
System.out.println(environment.getProperty("book.author"));
}
Bean的初始化和销毁
两种方式,java配置方式,注解方式
java配置方式
@Bean(initMethod="init",destroyMethod="destroy")
BeanWayService beanWayService(){
return new BeanWayService();
}
public class BeanWayService {
public void init() {
// do something
}
public void destroy() {
// do something
}
}
注解方式
利用JSR-250 的@PostConstruct和@PreDestroy
1. 增加JSR250支持
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
边学习边整理,待完善
参考:汪云飞 Spring Boot 实战