码迷,mamicode.com
首页 > 其他好文 > 详细

@Configuration、@EnableAsync 异步调用

时间:2018-12-08 16:59:16      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:[]   javac   run   word   多线程   安全   cme   还需要   com   

下面是一个典型的Spring配置文件(application-config.xml):

 

<beans> 
        <bean id="orderService" class="com.acme.OrderService"/> 
                <constructor-arg ref="orderRepository"/> 
        </bean> 
        <bean id="orderRepository" class="com.acme.OrderRepository"/> 
                <constructor-arg ref="dataSource"/> 
        </bean> 
</beans> 

然后你就可以像这样来使用是bean了:

ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml"); 

OrderService orderService = (OrderService) ctx.getBean("orderService"); 

现在Spring Java Configuration这个项目提供了一种通过java代码来装配bean的方案:

@Configuration 
public class ApplicationConfig { 
   
        public @Bean OrderService orderService() { 
                return new OrderService(orderRepository()); 
        } 
   
        public @Bean OrderRepository orderRepository() { 
                return new OrderRepository(dataSource()); 
        } 
   
        public @Bean DataSource dataSource() { 
                // instantiate and return an new DataSource … 
        } 
} 

然后你就可以像这样来使用是bean了:

JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class); 

OrderService orderService = ctx.getBean(OrderService.class);

这么做有什么好处呢?

     1.使用纯java代码,不在需要xml

     2.在配置中也可享受OO带来的好处

     3.类型安全对重构也能提供良好的支持

     4.依旧能享受到所有springIoC容器提供的功能

 

 ★

  EnableAsync注解的意思是可以异步执行,就是开启多线程的意思。可以标注在方法、类上。

 

@Component
public class Task {

    @Async
    public void doTaskOne() throws Exception {
        // 同上内容,省略
    }
}

为了让@Async注解能够生效,还需要在Spring Boot的主程序中配置@EnableAsync,如下所示:

@SpringBootApplication
@EnableAsync
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

注: @Async所修饰的函数不要定义为static类型,这样异步调用不会生效

@Configuration、@EnableAsync 异步调用

标签:[]   javac   run   word   多线程   安全   cme   还需要   com   

原文地址:https://www.cnblogs.com/hahajava/p/10088040.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
分享档案
周排行
mamicode.com排行更多图片
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!