bean配置类的注解开发
问题提出
用类充当配置文件 applicationcontext.xml :
@Configuration注解标识此类为配置类,替代原有xml文件
看原配置文件applicationcontext.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!--注解组件扫描: 扫描的指定基本包及其包下的类,识别使用@component注解--><context:component-scan base-package="com.itheima"/><context:property-placeholder location="classpath:jdbc.properties"/></beans>
这是bean配置类的文件SpringConfig(Java文件)
package com.itheima.config;import com.itheima.beans.OtherBean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;@Configuration //标注当前类是一个配置类(替代配置文件) +@Component
//<context:component-scan base-package="com.itheima"/> 配置组件扫描
@ComponentScan({"com.itheima"})
//<context:property-placeholder location="classpath:jdbc.properties"/> 配置properties加载
@PropertySource("classpath:jdbc.properties")
//<import resource=""></import>
@Import(OtherBean.class)
public class SpringConfig {}
@ComponentScan({"com.itheima"})
组件扫描配置:扫描包
@PropertySource("classpath:jdbc.properties")
加载外部资源properties
@Import(OtherBean.class)
导入其他配置类