@Configuration的使用
AppConfig.java
package com.web.spring.other;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource(
"classpath*:spring/spring-properties.xml")
public class AppConfig {
    
private @Value("${jdbc.driverClassName}") String driverClassName;
    @Bean(initMethod 
= "init")
    
public JDBCBean jdbc(){
        JDBCBean jdbc
=new JDBCBean();
        jdbc.setDriverClassName(driverClassName);
        
return jdbc;
    }

}

在xml中包含以上配置
xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation
="http://www.springframework.org/schema/beans   
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
            http://www.springframework.org/schema/context  
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:annotation-config/>
    
<!-- picks up and registers AppConfig as a bean definition -->
    
<context:component-scan base-package="com.web.spring.other" />
    
<context:property-placeholder location="classpath:jdbc.properties" />
    
<bean class="com.web.spring.other.AppConfig"/>
</beans>




使用@Configuration注解需要依赖CGLIB的JAR包
否则异常

Exception in thread "main" java.lang.IllegalStateException: CGLIB is required to process @Configuration classes. 
Either add CGLIB to the classpath or remove the following @Configuration bean definitions: [spring3HelloWorldConfig]

at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:257)

at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:147)

at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:624)

at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:614)

at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:398)

at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:65)

at net.roseindia.Spring3HelloWorldConfigTest.main(Spring3HelloWorldConfigTest.java:9)

posted on 2010-09-29 11:45 岁月神偷 阅读(5083) 评论(0)  编辑  收藏 所属分类: Spring

只有注册用户登录后才能发表评论。


网站导航: