欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

开发颠覆者SpringBoot实战---------Spring的基础学习

程序员文章站 2022-03-03 12:37:30
...

pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>myspringboot</groupId>
  <artifactId>spring4</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <!-- java编译级别 -->
  <properties>
    <java.version>1.7</java.version>
  </properties>
  <dependencies>
    <!-- spring容器(bean) -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>
    <!-- spring aop支持和aspectj依赖 -->
    <!-- Aspectj是aop的java实现方案,AspectJ是一种编译期的用注解形式实现的AOP -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.8.5</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.5</version>
    </dependency>
    <!-- 增加commons-io可简化文件相关操作 -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.3</version>
    </dependency>
    <!-- 增加JSR250支持,这是注解 -->
    <dependency>
        <groupId>javax.annotation</groupId>
        <artifactId>jsr250-api</artifactId>
        <version>1.0</version>
    </dependency>
    <!-- Spring test支持 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>4.1.6.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
  </dependencies>
  <!-- maven编译级别 -->
  <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
  </build>
</project>

一、依赖注入(bean)

/**
 * 功能类的bean
 * @author think
 */
@Service
public class FunctionService {
    public String sayHello(String str){
        return "hello " + str + "!";
    }
}

/**
 * 使用功能类的bean
 * @author think
 */
@Service
public class UseFunctionService {
    @Autowired
    private FunctionService service;
    public String sayHello(String str){
        return service.sayHello(str);
    }
}

/**
 * 配置
 * @author think
 */
@Configuration//声明注解类
@ComponentScan("com.CreateBeanTest.service")//扫描的包
public class DiConfig {
}

/**
 * 执行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DiConfig.class);
        UseFunctionService service = context.getBean(UseFunctionService.class);
        System.out.println(service.sayHello("spring学习"));
        context.close();
    }
}

二、AOP

/**
 * 自定义注解类
 * @author think
 */
@Target(ElementType.METHOD)//注解使用范围,使用在方法上
@Retention(RetentionPolicy.RUNTIME)//注解将保留到运行时
@Documented//表明这个注解应该被 javadoc工具记录,会被包括在生成的文档
public @interface Action {
    String name();
}

/**
 * 切面类
 * @author think
 */
@Aspect//声明这是切面
@Component//让切面成为spring容器管理的bean
public class LogAspect {
    @Pointcut("@annotation(com.AopTest.aspect.Action)")//声明切点
    public void annotationPointCut(){}
    @After("annotationPointCut()")
    public void after(JoinPoint point){
        MethodSignature sign = (MethodSignature) point.getSignature();
        Method method = sign.getMethod();
        Action action = method.getAnnotation(Action.class);
        System.out.println("注解式拦截:" + action.name());
    }
    @Before("execution(* com.AopTest.service.*.*(..))")
    public void before(JoinPoint point){
        MethodSignature sign = (MethodSignature) point.getSignature();
        Method method = sign.getMethod();
        System.out.println("方法规则式式拦截:" + method.getName());
    }
}

/**
 * 使用注解的被拦截类
 * @author think
 */
@Service
public class AnnotationService {
    @Action(name = "注解式拦截")
    public void add(){}
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.AopTest")
@EnableAspectJAutoProxy//开启spring对aspectj代理的支持
public class AopConfig {
}

/**
 * 执行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
        AnnotationService service = context.getBean(AnnotationService.class);
        service.add();
        context.close();
    }
}

三、scope

/**
 * prototype的bean
 * @author think
 */
@Service
@Scope("prototype")
public class PrototypeService {
}

/**
 * singleton的bean
 * @author think
 */
@Service
@Scope("singleton")//默认不需要写
public class SingletonService {
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.ScopeTest.service")
public class ScopeConfig {
}

/**
 * 执行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
        SingletonService singletonService1 = context.getBean(SingletonService.class);
        SingletonService singletonService2 = context.getBean(SingletonService.class);
        PrototypeService prototypeService1 = context.getBean(PrototypeService.class);
        PrototypeService prototypeService2 = context.getBean(PrototypeService.class);
        System.out.println(singletonService1);
        System.out.println(singletonService2);
        System.out.println(prototypeService1);
        System.out.println(prototypeService2);
        context.close();
    }
}

四、El和资源调用

需要生成两个文件test.txt和text.properties

/**
 * 一个测试service,用来获取类的属性
 * @author think
 */
@Service
public class TestService {
    @Value("其他类的属性")
    private String otherString;
    public String getOtherString() {
        return otherString;
    }
    public void setOtherString(String otherString) {
        this.otherString = otherString;
    }
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.ElTest")
@PropertySource("classpath:com/ElTest/test.properties")//指定文件地址
public class ElConfig {
    @Value("i love you")//注入普通字符串
    private String normal;
    @Value("#{systemProperties['os.name']}")//注入系统属性
    private String osName;
    @Value("#{testService.otherString}")//注入其他bean属性
    private String otherString;
    @Value("#{T(java.lang.Math).random()*100.0}")//注入表达式结果
    private String randomNumber;
    @Value("classpath:com/ElTest/test.txt")//注入文件资源
    private Resource testFile;
    @Value("http://www.baidu.com")//注入网站资源
    private Resource testUrl;
    @Value("${author.name}")//注入配置文件
    private String authorName;
    @Autowired
    private Environment environment;//注入系统环境变量
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigure(){
        return new PropertySourcesPlaceholderConfigurer();
    }
    public void outputResource() throws IOException{
        System.out.println(normal);
        System.out.println(osName);
        System.out.println(otherString);
        System.out.println(randomNumber);
        System.out.println(IOUtils.toString(testFile.getInputStream()));
        System.out.println(IOUtils.toString(testUrl.getInputStream()));
        System.out.println(authorName);
        System.out.println(environment.getProperty("author.sex"));
    }
}

/**
 * 执行
 * @author think
 */
public class Main {
    public static void main(String[] args) throws IOException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ElConfig.class);
        ElConfig config = context.getBean(ElConfig.class);
        config.outputResource();
        context.close();
    }
}

五、bean的创建和销毁

/**
 * 传统的bean形式,使用initMethod和destroyMethod
 * @author think
 */
public class BeanService {
    public void init(){
        System.out.println("bean创建");
    }
    public BeanService(){
        System.out.println("BeanService构造函数初始化");
    }
    public void destory(){
        System.out.println("bean销毁");
    }
}

/**
 * 使用JSR250注解来创建和销毁
 * @author think
 */
public class JSR250Service {
    @PostConstruct//在构造函数执行完后执行
    public void init(){
        System.out.println("jsr250创建");
    }
    public JSR250Service(){
        System.out.println("JSR250Service构造函数初始化");
    }
    @PreDestroy//在bean销毁之前执行
    public void destory(){
        System.out.println("jsr250销毁");
    }
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.InitAndDstoryBeanTest")
public class PrePostConfig {
    @Bean(initMethod="init",destroyMethod="destory")
    public BeanService beanService(){
        return new BeanService();
    }
    @Bean
    public JSR250Service jsr250Service(){
        return new JSR250Service();
    }
}

/**
 * 执行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrePostConfig.class);
        BeanService beanService = context.getBean(BeanService.class);
        JSR250Service jsr250Service = context.getBean(JSR250Service.class);
        context.close();
    }
}

六、时间event

/**
 * 自定义事件
 * @author think
 */
public class Event extends ApplicationEvent{
    private String msg;
    public Event(Object source, String msg) {
        super(source);
        this.msg = msg;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

/**
 * 事件监听器
 * @author think
 */
@Component
public class Listener implements ApplicationListener<Event>{
    @Override
    public void onApplicationEvent(Event event) {
        String msg = event.getMsg();
        System.out.println("接收到msg :" + msg);
    }
}

/**
 * 事件发布
 * @author think
 */
@Component
public class Publisher {
    @Autowired
    public ApplicationContext context;
    public void publish(String msg){
        context.publishEvent(new Event(this, msg));
    }
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.EventTest")
public class EventConfig {
}

/**
 * 执行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
        Publisher publisher = context.getBean(Publisher.class);
        publisher.publish("哈哈");
        context.close();
    }
}

七、Scheduled计划任务

/**
 * 执行计划任务类
 * @author think
 */
@Service
public class ScheduledTaskService {
    private static final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    @Scheduled(fixedRate = 5000)//间隔时间执行
    public void reportCurrentTime(){
        System.out.println("每五秒执行:" + format.format(new Date()));
    }
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.ScheduledTest")
@EnableScheduling//开启对计划任务的支持
public class ScheduledConfig {
}

/**
 * 执行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScheduledConfig.class);
    }
}

八、多线程

/**
 * 任务执行类
 * @author think
 */
@Service
public class AsynTaskService {
    @Async//表明这是一个异步方法,会被自动注入taskExecutor
    public void executeAsyncTask(Integer i){
        System.out.println("执行异步任务:" + i);
    }
}

/**
 * 配置
 * @author think
 */
@Configuration
@ComponentScan("com.TaskExecutorTest")
@EnableAsync//开启异步任务支持
public class TaskExecutorConfig implements AsyncConfigurer{
    @Override
    public Executor getAsyncExecutor() {//获得一个基于线程池的teskExecutor
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(25);
        executor.initialize();
        return executor;
    }
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

/**
 * 执行
 * @author think
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
        AsynTaskService asynTaskService = context.getBean(AsynTaskService.class);
        for (int i = 0; i < 10; i++) {
            asynTaskService.executeAsyncTask(i);
        }
        context.close();
    }
}

附:@Enable注解的使用*

  • @EnableAspectJAutoProxy ———- 开启spring对aspectj代理的支持
  • @EnableScheduling ———- 开启对计划任务的支持
  • @EnableAsync ———- 开启异步任务支持
  • @EnableWebMvc ———- 开启web mvc的配置支持
  • @EnableConfigurationProperties ———- 配置bean的支持
  • @EnableJpaRepositories ———- Spring Data Jpa的支持
  • @EnableTransactionManagement ———- 注解式事务的支持
  • @EnableCaching ———- 开启缓存支持
相关标签: spring基础