13,Spring - 基于注解的spring应用(bean的配置类开发)

在这里插入图片描述

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);
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值