org.springframework.context.annotation.AnnotationConfigApplicationContext.getBean()

Here are the examples of the java api org.springframework.context.annotation.AnnotationConfigApplicationContext.getBean() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

748 Examples 7

19 Source : Application.java
with GNU General Public License v3.0
from zhonghuasheng

public static void main(String[] args) {
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.clreplaced);
    ;
    AsyncTaskService asyncTaskService = appContext.getBean(AsyncTaskService.clreplaced);
    for (int i = 0; i < 10; i++) {
        asyncTaskService.executeAsyncTask(i);
        asyncTaskService.executeAsyncAddTask(i);
    }
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    // 如下代码并不能中断程序的运行
    /*AppConfig appConfig = appContext.getBean(AppConfig.clreplaced);
        ThreadPoolTaskExecutor threadPool = (ThreadPoolTaskExecutor) appConfig.getAsyncExecutor();
        threadPool.shutdown();*/
    appContext.close();
/**
 * 执行的结果并不是同步执行,而是异步执行
 *  Execute async task: 0
 *  4
 *  Execute async task: 3
 *  6
 *  Execute async task: 4
 *  8
 *  Execute async task: 5
 *  10
 *  Execute async task: 6
 *  12
 *  Execute async task: 7
 *  14
 *  Execute async task: 8
 *  16
 *  Execute async task: 9
 *  18
 */
}

19 Source : Application.java
with GNU General Public License v3.0
from zhonghuasheng

public static void main(String[] args) {
    // 调用方式一。VM配置-Dspring.profiles.active=dev
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.clreplaced);
    appContext.getBean(DataSource.clreplaced);
    appContext.close();
// 调用方式二。必须要先设置使用哪个环境dev/prod,否则在初始化bean的时候容器不知道选哪个
/*AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.clreplaced);
        appContext.getEnvironment().setActiveProfiles("dev");
        appContext.scan("com.zhonghuasheng.spring4.profile");
        appContext.close();*/
}

19 Source : Application.java
with GNU General Public License v3.0
from zhonghuasheng

public static void main(String[] args) {
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.clreplaced);
    UserService userService = appContext.getBean(UserService.clreplaced);
    userService.add();
    appContext.close();
}

19 Source : Application.java
with GNU General Public License v3.0
from zhonghuasheng

public static void main(String[] args) {
    /**
     * 与di不同,FunctionService和UserFunctionService都没有使用注解,在JavaConfig中通过@Configuration
     * 注解来说明这是一个配置类,@Bean注解在方法上,声明当前方法的返回值是一个bean
     */
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(JavaConfig.clreplaced);
    UserFunctionService userFunctionService = appContext.getBean(UserFunctionService.clreplaced);
    userFunctionService.say("Java Config");
    appContext.close();
}

19 Source : Application.java
with GNU General Public License v3.0
from zhonghuasheng

public static void main(String[] args) {
    /**
     * 1. 自定义事件,继承ApplicationEvent
     * 2. 定义事件监听器,实现ApplicationListener
     */
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.clreplaced);
    LogEventPublisher logEventPublisher = appContext.getBean(LogEventPublisher.clreplaced);
    logEventPublisher.publishLogEvent("test");
    appContext.close();
/**
 * LogEventListener handle this event:test
 * TrackingLogListener handle this event: test
 */
}

19 Source : Application.java
with GNU General Public License v3.0
from zhonghuasheng

public static void main(String[] args) throws IOException {
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.clreplaced);
    UseResourceService useResourceService = appContext.getBean(UseResourceService.clreplaced);
    useResourceService.printResource();
}

19 Source : Application.java
with GNU General Public License v3.0
from zhonghuasheng

public static void main(String[] args) {
    /**
     * Spring IoC容器(ApplicationContext)负责创建Bean,并通过容器将功能类Bean注入到你需要的Bean中。
     * 这里传入的参数是DIConfig.clreplaced,表示的annotatedClreplaced
     * DIConfig.clreplaced中通过@Configuration注解表示这是一个配置类bean,@ComponentScan注解将会自动扫描包
     * 名下所有使用@Service,@Component,@Repository和@Controller的类,并注册为Bean。
     */
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(DIConfig.clreplaced);
    // 通过IOC容器来获取自己想要的bean
    UserFunctionService userFunctionService = appContext.getBean(UserFunctionService.clreplaced);
    userFunctionService.say("DI");
    appContext.close();
}

19 Source : Application.java
with GNU General Public License v3.0
from zhonghuasheng

public static void main(String[] args) {
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.clreplaced);
    System.out.println(appContext.getEnvironment().getProperty("os.name"));
    CommandShow commandShow = appContext.getBean(CommandShow.clreplaced);
    commandShow.showListCmd();
}

19 Source : Application.java
with GNU General Public License v3.0
from zhonghuasheng

public static void main(String[] args) {
    /**
     * Scope描述的是Spring容器如何新建Bean的实例的。Spring的Scope有以下几种,通过@Scope注解来实现。
     * (1) Singleton:一个Spring容器中只有一个Bean的实例,此为Spring的默认配置,全容器共享一个实例。
     * (2) Prototype:每次调用新建一个Bean的实例。
     * (3) Request:Web项目中,给每一个http request新建一个bean实例。
     * (4) Session:Web项目中,给每一个http session新建一个bean实例。
     * (5) GlobalSession:这个只在portal应用中有用,给每一个global http session新建一个bean实例。
     * 另外,在Spring Batch中还有一个Scope是使用@StepScope。
     * 下面简单演示默认的singleton和prototype,分别从Spring容器中获得2次Bean,判断Bean的实例是否相等。
     */
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.clreplaced);
    UserSingleService userSingleService1 = appContext.getBean(UserSingleService.clreplaced);
    UserSingleService userSingleService2 = appContext.getBean(UserSingleService.clreplaced);
    UserPrototypeService userPrototypeService1 = appContext.getBean(UserPrototypeService.clreplaced);
    UserPrototypeService userPrototypeService2 = appContext.getBean(UserPrototypeService.clreplaced);
    // true
    System.out.println(userSingleService1 == userSingleService2);
    // false
    System.out.println(userPrototypeService1 == userPrototypeService2);
    appContext.close();
}

19 Source : Application.java
with GNU General Public License v3.0
from zhonghuasheng

public static void main(String[] args) {
    /**
     * 在我们进行实际开发的时候,经常遇到在Bean之前使用之前或者之后做些必要的操作,
     * Spring对Bean的生命周期的操作提供了支持。在使用Java配置和注解配置下提供如下两种方式:
     *
     * 1. Java配置方式:使用@Bean的initMethod和destroyMethod(相当于xml配置的init-method和destory-method)。
     * 2. 注解方式:利用JSR-250的@PostConstruct和@PreDestroy
     */
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.clreplaced);
    UserService userService = appContext.getBean(UserService.clreplaced);
    appContext.close();
/**
 * UserService Constructor
 * UserService init method
 * BeanWayUserService Constructor
 * BeanWayUserService init method
 * BeanWayUserService destroy
 * UserService destroy method
 */
}

19 Source : Application.java
with GNU General Public License v3.0
from zhonghuasheng

public static void main(String[] args) {
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.clreplaced);
    AwareService awareService = appContext.getBean(AwareService.clreplaced);
    awareService.print();
    appContext.close();
}

19 Source : Application.java
with GNU General Public License v3.0
from zhonghuasheng

public static void main(String[] args) {
    AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(AopConfig.clreplaced);
    UserService userService = appContext.getBean(UserService.clreplaced);
    NoAnnotationUserService noAnnotationUserService = appContext.getBean(NoAnnotationUserService.clreplaced);
    userService.register(new User("User1"));
    noAnnotationUserService.register(new User("User2"));
    appContext.close();
/**
 * AnnotationPointCut执行之前
 * User{name='User1'}
 * AnnotationPointCut执行之后User注解式拦截register方法
 * 可以在这个方法执行之前做些什么register
 * 二月 21, 2020 6:32:01 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
 * 信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@1d56ce6a: startup date [Fri Feb 21 18:32:00 CST 2020]; root of context hierarchy
 * User{name='User2'}
 */
}

19 Source : ConditionTest.java
with Apache License 2.0
from yuanmabiji

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.clreplaced);
    ListService listService = context.getBean(ListService.clreplaced);
    System.out.println(context.getEnvironment().getProperty("os.name") + " 系统下的列表命令为: " + listService.showListLine());
}

19 Source : EmbeddedJarStarter.java
with Apache License 2.0
from yuanmabiji

public static void main(String[] args) throws Exception {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.clreplaced);
    context.getBean(SpringConfiguration.clreplaced).run(args);
    context.close();
}

19 Source : ThymeleafServletAutoConfigurationTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void renderNonWebAppTemplate() {
    try (AnnotationConfigApplicationContext customContext = new AnnotationConfigApplicationContext(ThymeleafAutoConfiguration.clreplaced, PropertyPlaceholderAutoConfiguration.clreplaced)) {
        replacedertThat(customContext.getBeanNamesForType(ViewResolver.clreplaced).length).isEqualTo(0);
        TemplateEngine engine = customContext.getBean(TemplateEngine.clreplaced);
        Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World"));
        String result = engine.process("message", attrs);
        replacedertThat(result).contains("Hello World");
    }
}

19 Source : MongoPropertiesTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void canBindCharArrayPreplacedword() {
    // gh-1572
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    TestPropertyValues.of("spring.data.mongodb.preplacedword:word").applyTo(context);
    context.register(Config.clreplaced);
    context.refresh();
    MongoProperties properties = context.getBean(MongoProperties.clreplaced);
    replacedertThat(properties.getPreplacedword()).isEqualTo("word".toCharArray());
}

19 Source : GateWayApplication.java
with Apache License 2.0
from XiaoMi

public static void main(String[] args) {
    log.info("gateway start version:{}", new GateWayVersion());
    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(GateWayApplication.clreplaced, ApplicationContextConfig.clreplaced, DubboConfiguration.clreplaced);
    try {
        DubboCat.enable();
        Dispatcher dispatcher = ac.getBean(Dispatcher.clreplaced);
        RequestFilterChain filterChain = ac.getBean(RequestFilterChain.clreplaced);
        ApiRouteCache apiRouteCache = ac.getBean(ApiRouteCache.clreplaced);
        DubboConfiguration dubboConfiguration = ac.getBean(DubboConfiguration.clreplaced);
        log.info("gateway runing");
        new GateWayApplication().run(dispatcher, filterChain, apiRouteCache, dubboConfiguration);
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        System.exit(-1);
    }
}

19 Source : EnableTransactionManagementIntegrationTests.java
with MIT License
from Vip-Augus

private void replacedertTxProxying(AnnotationConfigApplicationContext ctx) {
    FooRepository repo = ctx.getBean(FooRepository.clreplaced);
    boolean isTxProxy = false;
    if (AopUtils.isAopProxy(repo)) {
        for (Advisor advisor : ((Advised) repo).getAdvisors()) {
            if (advisor instanceof BeanFactoryTransactionAttributeSourceAdvisor) {
                isTxProxy = true;
                break;
            }
        }
    }
    replacedertTrue("FooRepository is not a TX proxy", isTxProxy);
    // trigger a transaction
    repo.findAll();
}

19 Source : ApplicationContextExpressionTests.java
with MIT License
from Vip-Augus

@Test
public void resourceInjection() throws IOException {
    System.setProperty("logfile", "do_not_delete_me.txt");
    try (AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ResourceInjectionBean.clreplaced)) {
        ResourceInjectionBean resourceInjectionBean = ac.getBean(ResourceInjectionBean.clreplaced);
        Resource resource = new ClreplacedPathResource("do_not_delete_me.txt");
        replacedertEquals(resource, resourceInjectionBean.resource);
        replacedertEquals(resource.getURL(), resourceInjectionBean.url);
        replacedertEquals(resource.getURI(), resourceInjectionBean.uri);
        replacedertEquals(resource.getFile(), resourceInjectionBean.file);
        replacedertArrayEquals(FileCopyUtils.copyToByteArray(resource.getInputStream()), FileCopyUtils.copyToByteArray(resourceInjectionBean.inputStream));
        replacedertEquals(FileCopyUtils.copyToString(new EncodedResource(resource).getReader()), FileCopyUtils.copyToString(resourceInjectionBean.reader));
    } finally {
        System.getProperties().remove("logfile");
    }
}

19 Source : ApplicationContextExpressionTests.java
with MIT License
from Vip-Augus

@Test
public void stringConcatenationWithDebugLogging() {
    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
    GenericBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClreplaced(String.clreplaced);
    bd.getConstructorArgumentValues().addGenericArgumentValue("test-#{ T(java.lang.System).currentTimeMillis() }");
    ac.registerBeanDefinition("str", bd);
    ac.refresh();
    String str = ac.getBean("str", String.clreplaced);
    replacedertTrue(str.startsWith("test-"));
}

19 Source : ApplicationContextExpressionTests.java
with MIT License
from Vip-Augus

@Test
public void systemPropertiesSecurityManager() {
    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
    GenericBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClreplaced(TestBean.clreplaced);
    bd.getPropertyValues().add("country", "#{systemProperties.country}");
    ac.registerBeanDefinition("tb", bd);
    SecurityManager oldSecurityManager = System.getSecurityManager();
    try {
        System.setProperty("country", "NL");
        SecurityManager securityManager = new SecurityManager() {

            @Override
            public void checkPropertiesAccess() {
                throw new AccessControlException("Not Allowed");
            }

            @Override
            public void checkPermission(Permission perm) {
            // allow everything else
            }
        };
        System.setSecurityManager(securityManager);
        ac.refresh();
        TestBean tb = ac.getBean("tb", TestBean.clreplaced);
        replacedertEquals("NL", tb.getCountry());
    } finally {
        System.setSecurityManager(oldSecurityManager);
        System.getProperties().remove("country");
    }
}

19 Source : ConfigurationClassProcessingTests.java
with MIT License
from Vip-Augus

@Test
public void configurationWithFunctionalRegistration() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(ConfigWithFunctionalRegistration.clreplaced);
    ctx.refresh();
    replacedertSame(ctx.getBean("spouse"), ctx.getBean(TestBean.clreplaced).getSpouse());
    replacedertEquals("functional", ctx.getBean(NestedTestBean.clreplaced).getCompany());
}

19 Source : ConfigurationClassProcessingTests.java
with MIT License
from Vip-Augus

@Test
public void configurationWithAdaptivePrototypes() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(ConfigWithPrototypeBean.clreplaced, AdaptiveInjectionPoints.clreplaced);
    ctx.refresh();
    AdaptiveInjectionPoints adaptive = ctx.getBean(AdaptiveInjectionPoints.clreplaced);
    replacedertEquals("adaptiveInjectionPoint1", adaptive.adaptiveInjectionPoint1.getName());
    replacedertEquals("setAdaptiveInjectionPoint2", adaptive.adaptiveInjectionPoint2.getName());
    adaptive = ctx.getBean(AdaptiveInjectionPoints.clreplaced);
    replacedertEquals("adaptiveInjectionPoint1", adaptive.adaptiveInjectionPoint1.getName());
    replacedertEquals("setAdaptiveInjectionPoint2", adaptive.adaptiveInjectionPoint2.getName());
    ctx.close();
}

19 Source : ConfigurationClassProcessingTests.java
with MIT License
from Vip-Augus

@Test
public void configurationWithAdaptiveResourcePrototypes() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(ConfigWithPrototypeBean.clreplaced, AdaptiveResourceInjectionPoints.clreplaced);
    ctx.refresh();
    AdaptiveResourceInjectionPoints adaptive = ctx.getBean(AdaptiveResourceInjectionPoints.clreplaced);
    replacedertEquals("adaptiveInjectionPoint1", adaptive.adaptiveInjectionPoint1.getName());
    replacedertEquals("setAdaptiveInjectionPoint2", adaptive.adaptiveInjectionPoint2.getName());
    adaptive = ctx.getBean(AdaptiveResourceInjectionPoints.clreplaced);
    replacedertEquals("adaptiveInjectionPoint1", adaptive.adaptiveInjectionPoint1.getName());
    replacedertEquals("setAdaptiveInjectionPoint2", adaptive.adaptiveInjectionPoint2.getName());
    ctx.close();
}

19 Source : ZipkinServerConfigurationTest.java
with Apache License 2.0
from Tanzu-Solutions-Engineering

@Test(expected = NoSuchBeanDefinitionException.clreplaced)
public void httpCollector_canDisable() {
    addEnvironment(context, "zipkin.collector.http.enabled:false");
    context.register(PropertyPlaceholderAutoConfiguration.clreplaced, ZipkinServerConfigurationTest.Config.clreplaced, ZipkinServerConfiguration.clreplaced, ZipkinHttpCollector.clreplaced);
    context.refresh();
    context.getBean(ZipkinHttpCollector.clreplaced);
}

19 Source : MainApp.java
with Apache License 2.0
from StnetixDevTeam

public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(CoreConfig.clreplaced);
    IUi ui = ctx.getBean(IUi.clreplaced);
    ui.startUi(args);
}

19 Source : AbstractVaultConfigurationUnitTests.java
with Apache License 2.0
from spring-projects

@Test
void shouldApplyCustomizerToRestTemplateFactory() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RestTemplateCustomizerConfiguration.clreplaced);
    RestTemplateFactory factory = context.getBean(RestTemplateFactory.clreplaced);
    RestTemplate restTemplate = factory.create();
    replacedertThatExceptionOfType(CustomizedSignal.clreplaced).isThrownBy(() -> restTemplate.delete("/foo"));
}

19 Source : LeaseAwareVaultPropertySourceIntegrationTests.java
with Apache License 2.0
from spring-projects

@Test
void shouldLoadProperties() {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.clreplaced, PropertyConsumer.clreplaced)) {
        ConfigurableEnvironment env = context.getEnvironment();
        PropertyConsumer consumer = context.getBean(PropertyConsumer.clreplaced);
        replacedertThat(env.getProperty("myapp")).isEqualTo("myvalue");
        replacedertThat(env.getProperty("myprofile")).isEqualTo("myprofilevalue");
        replacedertThat(consumer.myapp).isEqualTo("myvalue");
    }
}

19 Source : Application.java
with Apache License 2.0
from spring-projects

public static void main(String[] args) throws Exception {
    try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Application.clreplaced)) {
        context.getBean(NettyContext.clreplaced).onClose().block();
    }
}

19 Source : BeanDefinitionInheritanceDemoApplication.java
with GNU General Public License v3.0
from spring-framework-guru

public static void main(String[] args) {
    // XML based Bean Definition Test\
    System.out.println("XML based Bean Definition Inheritance Test");
    ApplicationContext context = new ClreplacedPathXmlApplicationContext("beans.xml");
    Book book = (Book) context.getBean("BookBean");
    System.out.println("Book Details: " + book);
    // Annotation based Bean Definition Test
    System.out.println("Annotation based Bean Definition Inheritance Test");
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(AppConfig.clreplaced);
    ctx.refresh();
    EPubBook ePubBook = ctx.getBean(EPubBook.clreplaced);
    System.out.println("Author Name: " + ePubBook.getAuthorName());
    System.out.println("Book Name: " + ePubBook.getBookName());
    System.out.println("Book Price: " + ePubBook.getBookPrice());
    System.out.println("Download URL: " + ePubBook.getDownloadUrl());
    ctx.registerShutdownHook();
}

19 Source : EnableTransactionManagementTests.java
with Apache License 2.0
from SourceHot

@Test
public void spr14322FindsOnInterfaceWithInterfaceProxy() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Spr14322ConfigA.clreplaced);
    TransactionalTestInterface bean = ctx.getBean(TransactionalTestInterface.clreplaced);
    CallCountingTransactionManager txManager = ctx.getBean(CallCountingTransactionManager.clreplaced);
    bean.saveFoo();
    bean.saveBar();
    replacedertThat(txManager.begun).isEqualTo(2);
    replacedertThat(txManager.commits).isEqualTo(2);
    replacedertThat(txManager.rollbacks).isEqualTo(0);
    ctx.close();
}

19 Source : EnableTransactionManagementTests.java
with Apache License 2.0
from SourceHot

@Test
public void spr11915TransactionManagerAsManualSingleton() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Spr11915Config.clreplaced);
    TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.clreplaced);
    CallCountingTransactionManager txManager = ctx.getBean("qualifiedTransactionManager", CallCountingTransactionManager.clreplaced);
    bean.saveQualifiedFoo();
    replacedertThat(txManager.begun).isEqualTo(1);
    replacedertThat(txManager.commits).isEqualTo(1);
    replacedertThat(txManager.rollbacks).isEqualTo(0);
    bean.saveQualifiedFooWithAttributeAlias();
    replacedertThat(txManager.begun).isEqualTo(2);
    replacedertThat(txManager.commits).isEqualTo(2);
    replacedertThat(txManager.rollbacks).isEqualTo(0);
    ctx.close();
}

19 Source : EnableTransactionManagementTests.java
with Apache License 2.0
from SourceHot

@Test
public void spr14322FindsOnInterfaceWithCglibProxy() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Spr14322ConfigB.clreplaced);
    TransactionalTestInterface bean = ctx.getBean(TransactionalTestInterface.clreplaced);
    CallCountingTransactionManager txManager = ctx.getBean(CallCountingTransactionManager.clreplaced);
    bean.saveFoo();
    bean.saveBar();
    replacedertThat(txManager.begun).isEqualTo(2);
    replacedertThat(txManager.commits).isEqualTo(2);
    replacedertThat(txManager.rollbacks).isEqualTo(0);
    ctx.close();
}

19 Source : DeclarativeTransactionTest.java
with Apache License 2.0
from SourceHot

public static void main(String[] args) throws Exception {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TxConfig.clreplaced);
    IssueServiceImpl bean = applicationContext.getBean(IssueServiceImpl.clreplaced);
    bean.insertIssue();
    System.out.println();
    applicationContext.close();
}

19 Source : LoopBean.java
with Apache License 2.0
from SourceHot

public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(LoopBean.clreplaced);
    B bean = ctx.getBean(B.clreplaced);
    System.out.println();
// traverseFolder("D:\\desktop\\git_repo\\spring-ebk\\spring-framework-read\\doc\\book");
}

19 Source : BeanDefinitionDemo.java
with Apache License 2.0
from SourceHot

public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(BeanDefinitionDemo.clreplaced);
    Person person = ctx.getBean(Person.clreplaced);
    System.out.println(person.getName());
}

19 Source : AnnotationContextDemo.java
with Apache License 2.0
from SourceHot

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AnnotationContextDemo.clreplaced);
    Us bean = context.getBean(Us.clreplaced);
    context.close();
}

19 Source : EnableAsyncTests.java
with Apache License 2.0
from SourceHot

@Test
public void customExecutorBeanConfig() {
    // Arrange
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(CustomExecutorBeanConfig.clreplaced, ExecutorPostProcessor.clreplaced);
    ctx.refresh();
    AsyncBean asyncBean = ctx.getBean(AsyncBean.clreplaced);
    // Act
    asyncBean.work();
    // replacedert
    Awaitility.await().atMost(500, TimeUnit.MILLISECONDS).pollInterval(10, TimeUnit.MILLISECONDS).until(() -> asyncBean.getThreadOfExecution() != null);
    replacedertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Post-");
    ctx.close();
}

19 Source : EnableAsyncTests.java
with Apache License 2.0
from SourceHot

@Test
public void customExecutorConfig() {
    // Arrange
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(CustomExecutorConfig.clreplaced);
    ctx.refresh();
    AsyncBean asyncBean = ctx.getBean(AsyncBean.clreplaced);
    // Act
    asyncBean.work();
    // replacedert
    Awaitility.await().atMost(500, TimeUnit.MILLISECONDS).pollInterval(10, TimeUnit.MILLISECONDS).until(() -> asyncBean.getThreadOfExecution() != null);
    replacedertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Custom-");
    ctx.close();
}

19 Source : EnableAsyncTests.java
with Apache License 2.0
from SourceHot

// SPR-14949
@Test
public void findOnInterfaceWithCglibProxy() {
    // Arrange
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Spr14949ConfigB.clreplaced);
    AsyncInterface asyncBean = ctx.getBean(AsyncInterface.clreplaced);
    // Act
    asyncBean.work();
    // replacedert
    Awaitility.await().atMost(500, TimeUnit.MILLISECONDS).pollInterval(10, TimeUnit.MILLISECONDS).until(() -> asyncBean.getThreadOfExecution() != null);
    replacedertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Custom-");
    ctx.close();
}

19 Source : EnableAsyncTests.java
with Apache License 2.0
from SourceHot

@Test
public void proxyingOccursWithMockitoStub() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(AsyncConfigWithMockito.clreplaced, AsyncBereplaceder.clreplaced);
    ctx.refresh();
    AsyncBereplaceder asyncBereplaceder = ctx.getBean(AsyncBereplaceder.clreplaced);
    AsyncBean asyncBean = asyncBereplaceder.getAsyncBean();
    replacedertThat(AopUtils.isAopProxy(asyncBean)).isTrue();
    asyncBean.work();
    ctx.close();
}

19 Source : EnableAsyncTests.java
with Apache License 2.0
from SourceHot

// SPR-14949
@Test
public void findOnInterfaceWithInterfaceProxy() {
    // Arrange
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Spr14949ConfigA.clreplaced);
    AsyncInterface asyncBean = ctx.getBean(AsyncInterface.clreplaced);
    // Act
    asyncBean.work();
    // replacedert
    Awaitility.await().atMost(500, TimeUnit.MILLISECONDS).pollInterval(10, TimeUnit.MILLISECONDS).until(() -> asyncBean.getThreadOfExecution() != null);
    replacedertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Custom-");
    ctx.close();
}

19 Source : EnableAsyncTests.java
with Apache License 2.0
from SourceHot

@Test
public void customExecutorBeanConfigWithThrowsException() {
    // Arrange
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(CustomExecutorBeanConfig.clreplaced, ExecutorPostProcessor.clreplaced);
    ctx.refresh();
    AsyncBean asyncBean = ctx.getBean(AsyncBean.clreplaced);
    TestableAsyncUncaughtExceptionHandler exceptionHandler = (TestableAsyncUncaughtExceptionHandler) ctx.getBean("exceptionHandler");
    replacedertThat(exceptionHandler.isCalled()).as("handler should not have been called yet").isFalse();
    Method method = ReflectionUtils.findMethod(AsyncBean.clreplaced, "fail");
    // Act
    asyncBean.fail();
    // replacedert
    Awaitility.await().atMost(500, TimeUnit.MILLISECONDS).pollInterval(10, TimeUnit.MILLISECONDS).untilreplacederted(() -> exceptionHandler.replacedertCalledWith(method, UnsupportedOperationException.clreplaced));
    ctx.close();
}

19 Source : EnableAsyncTests.java
with Apache License 2.0
from SourceHot

@Test
public void proxyingOccurs() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(AsyncConfig.clreplaced);
    ctx.refresh();
    AsyncBean asyncBean = ctx.getBean(AsyncBean.clreplaced);
    replacedertThat(AopUtils.isAopProxy(asyncBean)).isTrue();
    asyncBean.work();
    ctx.close();
}

19 Source : EnableAsyncTests.java
with Apache License 2.0
from SourceHot

@Test
public void customAsyncAnnotationIsPropagated() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(CustomAsyncAnnotationConfig.clreplaced, CustomAsyncBean.clreplaced);
    ctx.refresh();
    Object bean = ctx.getBean(CustomAsyncBean.clreplaced);
    replacedertThat(AopUtils.isAopProxy(bean)).isTrue();
    boolean isAsyncAdvised = false;
    for (Advisor advisor : ((Advised) bean).getAdvisors()) {
        if (advisor instanceof AsyncAnnotationAdvisor) {
            isAsyncAdvised = true;
            break;
        }
    }
    replacedertThat(isAsyncAdvised).as("bean was not async advised as expected").isTrue();
    ctx.close();
}

19 Source : EnableAsyncTests.java
with Apache License 2.0
from SourceHot

@Test
public void customExecutorConfigWithThrowsException() {
    // Arrange
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(CustomExecutorConfig.clreplaced);
    ctx.refresh();
    AsyncBean asyncBean = ctx.getBean(AsyncBean.clreplaced);
    Method method = ReflectionUtils.findMethod(AsyncBean.clreplaced, "fail");
    TestableAsyncUncaughtExceptionHandler exceptionHandler = (TestableAsyncUncaughtExceptionHandler) ctx.getBean("exceptionHandler");
    replacedertThat(exceptionHandler.isCalled()).as("handler should not have been called yet").isFalse();
    // Act
    asyncBean.fail();
    // replacedert
    Awaitility.await().atMost(500, TimeUnit.MILLISECONDS).pollInterval(10, TimeUnit.MILLISECONDS).untilreplacederted(() -> exceptionHandler.replacedertCalledWith(method, UnsupportedOperationException.clreplaced));
    ctx.close();
}

19 Source : EnableAsyncTests.java
with Apache License 2.0
from SourceHot

@Test
public void withAsyncBeanWithExecutorQualifiedByName() throws ExecutionException, InterruptedException {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(AsyncWithExecutorQualifiedByNameConfig.clreplaced);
    ctx.refresh();
    AsyncBeanWithExecutorQualifiedByName asyncBean = ctx.getBean(AsyncBeanWithExecutorQualifiedByName.clreplaced);
    Future<Thread> workerThread0 = asyncBean.work0();
    replacedertThat(workerThread0.get().getName()).doesNotStartWith("e1-").doesNotStartWith("otherExecutor-");
    Future<Thread> workerThread = asyncBean.work();
    replacedertThat(workerThread.get().getName()).startsWith("e1-");
    Future<Thread> workerThread2 = asyncBean.work2();
    replacedertThat(workerThread2.get().getName()).startsWith("otherExecutor-");
    Future<Thread> workerThread3 = asyncBean.work3();
    replacedertThat(workerThread3.get().getName()).startsWith("otherExecutor-");
    ctx.close();
}

19 Source : EnableAsyncTests.java
with Apache License 2.0
from SourceHot

@Test
public void customExecutorBean() {
    // Arrange
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(CustomExecutorBean.clreplaced);
    ctx.refresh();
    AsyncBean asyncBean = ctx.getBean(AsyncBean.clreplaced);
    // Act
    asyncBean.work();
    // replacedert
    Awaitility.await().atMost(500, TimeUnit.MILLISECONDS).pollInterval(10, TimeUnit.MILLISECONDS).until(() -> asyncBean.getThreadOfExecution() != null);
    replacedertThat(asyncBean.getThreadOfExecution().getName()).startsWith("Custom-");
    ctx.close();
}

19 Source : ApplicationContextExpressionTests.java
with Apache License 2.0
from SourceHot

@Test
void stringConcatenationWithDebugLogging() {
    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
    GenericBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClreplaced(String.clreplaced);
    bd.getConstructorArgumentValues().addGenericArgumentValue("test-#{ T(java.lang.System).currentTimeMillis() }");
    ac.registerBeanDefinition("str", bd);
    ac.refresh();
    String str = ac.getBean("str", String.clreplaced);
    replacedertThat(str.startsWith("test-")).isTrue();
    ac.close();
}

19 Source : ApplicationContextExpressionTests.java
with Apache License 2.0
from SourceHot

@Test
void systemPropertiesSecurityManager() {
    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
    GenericBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClreplaced(TestBean.clreplaced);
    bd.getPropertyValues().add("country", "#{systemProperties.country}");
    ac.registerBeanDefinition("tb", bd);
    SecurityManager oldSecurityManager = System.getSecurityManager();
    try {
        System.setProperty("country", "NL");
        SecurityManager securityManager = new SecurityManager() {

            @Override
            public void checkPropertiesAccess() {
                throw new AccessControlException("Not Allowed");
            }

            @Override
            public void checkPermission(Permission perm) {
            // allow everything else
            }
        };
        System.setSecurityManager(securityManager);
        ac.refresh();
        TestBean tb = ac.getBean("tb", TestBean.clreplaced);
        replacedertThat(tb.getCountry()).isEqualTo("NL");
    } finally {
        System.setSecurityManager(oldSecurityManager);
        System.getProperties().remove("country");
    }
    ac.close();
}

See More Examples