注解
一.@Async 异步注解
注意点
1.启用该注解时需要在配置类或者启动类中添加 @EnableAsync
2.@Async 不能在同一个类中,应该新建立一个组件类
3.注解打在方法上作用域为该方法、打在类上时作用域为该类下所有的方法
@Component
@Async
public class AsyncDemo {
public void sendMsg(String msg) throws InterruptedException {
Thread.sleep(10000);
System.out.println("发送消息:"+msg);
}
public void sendMsg2(String msg) throws InterruptedException {
Thread.sleep(5000);
System.out.println("发送消息2:"+msg);
}
}
// 测试类
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
@EnableAsync
public class MyTest {
@Test
public void testaaa() throws InterruptedException {
asyncDemo.sendMsg("我是消息1");
asyncDemo.sendMsg2("我是消息2");
System.out.println("执行了....");
Thread.sleep(20000);
System.out.println("我是主线程执行完毕");
}
}
运行结果
执行了....
发送消息2:我是消息2
发送消息:我是消息1
我是主线程执行完毕
二.@Import 向容器总注入bean
三种使用方式:
2.1 直接注入
@Configuration
@Import(ImportOne.class)
public class ImportOneConfig {
}
public class ImportOne {
}
2.2 implements ImportSelector注入
public class ImportTwoSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[]{"com.example.test.myImport.ImportTwoSelectorA","com.example.test.myImport.ImportTwoSelectorB"}; } } public class ImportTwoSelectorA { } public class ImportTwoSelectorB { }
2.2 使用 Registrar
public class ImprortThreeBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) { RootBeanDefinition beanDefinition=new RootBeanDefinition(ImprortThreeBeanDefinitionRegistrarA.class); beanDefinitionRegistry.registerBeanDefinition("ImprortThreeBeanDefinitionRegistrarA",beanDefinition); } } public class ImprortThreeBeanDefinitionRegistrarA { } @Configuration @Import(ImprortThreeBeanDefinitionRegistrar.class) public class ImprortThreeBeanDefinitionRegistrarConfig { }

浙公网安备 33010602011771号