12,Spring - 基于注解的spring应用(非自定义bean的注解开发)

文章展示了如何在Java中创建一个名为OtherBean的组件,该组件使用DruidDataSource来配置数据源,并在Spring应用上下文中通过@Bean注解注册。测试类ApplicationContextDemo01演示了如何从应用上下文中获取并打印出dataSourcebean。
摘要由CSDN通过智能技术生成

在这里插入图片描述

1,代码演示

1.1 新建 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.2 修改测试类 ApplicationContextDemo01

package com.study.demo;

import com.study.service.UserService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationContextDemo01 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        Object dataSource = context.getBean("dataSource");
        System.out.println(dataSource);
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值