栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring boot注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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支持


    javax.annotation
    jsr250-api
    1.0

边学习边整理,待完善

参考:汪云飞 Spring Boot 实战

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/973120.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号