Spring JavaConfig Reference Guide 该文档所引入的包 spring-javaconfig 在Spring3.0之后不再使用,JavaConfig作为Spring核心的功能,JavaConfigApplicationContext 被替换为AnnotationConfigApplicationContet.br/>目前在项目中用到的xml与JavaConfig结合的方式使用,将数据库连接、路径扫描配置在XML中,有些bean通过@Bean进行将其放入到容器中。<br/
@Configuration @Bean/strong><br/><em>@Configuration</em 相当于XML中 code><beans/></code>元素,<em>@Bean</em相当于XML中的<bean/>
1 2 3 4 5 6 7 8 9 10
|
@Configuration public class AppConfig { @Autowired //直接引用其他的bean DateSource dataSource; @Bean public Animal animal() { return new Animal(); } }
|
相当于xml:bean.xml
1 2 3 4 5 6 7
|
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="animal" class="com.maxlcat.bean.Animal"></bean> </beans>
|
启动
1 2
|
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); System.out.println(context.getBean("animal"));
|
strong>@Import、@ImportResource</strong
1 2
|
@Import(DataConfig.class) @ImportResource("classpath:dataConfig.xml")
|
@ImportResource相当于xml文件中的
1
|
<import resource="dataConfig.xml" />
|
strong>@ComponentScan</strong
相当于xml文件中
1
|
<context:component-scan>
|
strong>@PropertySource</strong
读取配置文件的信息
1 2 3 4 5 6 7 8 9 10 11
|
@Configuration @PropertySource("bean.properties") public class AppConfig { @Autowired Environment env; @Bean public Animal animal() { return new Animal(env.getProperty("name")); } }
|
参考:Spring JavaConfig Reference Guide
http://stackoverflow.com/questions/7295642/spring-javaconfig-nosuchbeandefinitionexception-no-unique-bean-of-type/7295738#7295738
近期评论