spring boot注解

目录

依赖注入或控制反转(Ioc)

AOP

值注入

Bean的初始化和销毁


依赖注入或控制反转(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 实战

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值