![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0bbcac0a523f4f5ee57dc54042f0c4b6.png)
1,代码演示
1.1,新建配置类 SpringConfig
package com.study.config;
import com.study.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 //标注这个类是个配置类,用于替代配置文件
//替换 <context:component-scan base-package="com.study"/>
@ComponentScan("com.study")
//替换 <context:property-placeholder location="classpath:constant.properties"/>
@PropertySource("classpath:constant.properties")
//替换 <import resource=""/>
@Import(OtherBean.class)
public class SpringConfig {
}
1.2,修改 OtherBean
package com.study.beans;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
//@Component
public class OtherBean {
@Bean("dataSource")
public DataSource dataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
//设置基本参数 ...
return druidDataSource;
}
}
1.3,修改测试类
package com.study.demo;
import com.study.config.SpringConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class ApplicationContextDemo01 {
public static void main(String[] args) {
//xml方式
// ClassPathXmlApplicationContext context =
// new ClassPathXmlApplicationContext("applicationContext.xml");
//注解方式加载配置类
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
Object userService = applicationContext.getBean("userService");
System.out.println(userService);
Object dataSource = applicationContext.getBean("dataSource");
System.out.println(dataSource);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/393f32146350656d7064ec827090fbe5.png)