View Javadoc
1   /*
2    * Copyright 2002-2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.context.annotation;
18  
19  import org.junit.Test;
20  
21  import org.springframework.beans.factory.FactoryBean;
22  import org.springframework.beans.factory.annotation.Autowired;
23  import org.springframework.beans.factory.annotation.Value;
24  import org.springframework.context.ApplicationContext;
25  
26  import static org.junit.Assert.*;
27  
28  /**
29   * Test case cornering the bug initially raised with SPR-8762, in which a
30   * NullPointerException would be raised if a FactoryBean-returning @Bean method also
31   * accepts parameters
32   *
33   * @author Chris Beams
34   * @since 3.1
35   */
36  public class ConfigurationWithFactoryBeanAndParametersTests {
37  
38  	@Test
39  	public void test() {
40  		ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class, Bar.class);
41  		assertNotNull(ctx.getBean(Bar.class).foo);
42  	}
43  
44  
45  	@Configuration
46  	static class Config {
47  
48  		@Bean
49  		public FactoryBean<Foo> fb(@Value("42") String answer) {
50  			return new FooFactoryBean();
51  		}
52  	}
53  
54  
55  	static class Foo {
56  	}
57  
58  
59  	static class Bar {
60  
61  		Foo foo;
62  
63  		@Autowired
64  		public Bar(Foo foo) {
65  			this.foo = foo;
66  		}
67  	}
68  
69  
70  	static class FooFactoryBean implements FactoryBean<Foo> {
71  
72  		@Override
73  		public Foo getObject() {
74  			return new Foo();
75  		}
76  
77  		@Override
78  		public Class<Foo> getObjectType() {
79  			return Foo.class;
80  		}
81  
82  		@Override
83  		public boolean isSingleton() {
84  			return true;
85  		}
86  	}
87  
88  }