基于Java的容器注解@Bean

本文详细介绍了Spring框架中@Bean注解的使用方法,包括如何使用@Bean定义Bean、自定义Bean名称、定义初始化和销毁方法等。并通过示例代码展示了@Bean在实际应用中的配置方式。

日期: 2016-7-19


内容: Spring的@Bean注解


1、 @Beab标识一个用于配置和初始化一个由SpringIoC日那个气的新对象方法,类似于xml文件的<bean/>:


2、可以在Spring的@Component注解的类中使用@Bean注解任何方法(仅仅是可以),但是一般不用@Component,更常用的是@Configuration(一个配置类)。

@Configuration
public class AppConfig()
{
    @Bean
    public MyService myService()
    {
         return new MyServiceImpl();
    }
}

使用如上的注解相当于在配置文件中使用如下的配置:

<beans>
	<bean id="myService" class="com.hello.MyServiceImpl"></bean/>
</beans>


自定义Bean的name:

public class Foo
{
<span style="white-space:pre">	</span>//do somethings
}


@Configuration
public class AppConfig
{
<span style="white-space:pre">	</span>@Bean(name="myFoo")
<span style="white-space:pre">	</span>public Foo foo()
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>return new Foo();
<span style="white-space:pre">	</span>}
}


@Bean可以定义初始化方法和销毁方法: initMethod,destoryMethod;

public class Foo
{
	public void init()
	{
		System.out.println("我是初始化方法!");
	}
}

public class Bar()
{
	public void destory()
	{
		System.out.println("我执行了销毁方法!");
	}
}

//调用初始化和销毁方法配置
@Configuration
public class TestBean
{
	@Bean(initMethod="init")
	public Foo getFoo()
	{
		return new Foo();
	}

	@Bean(destoryMethod="destory")
	public void getBar()
	{
		return new Bar();
	}
}


实例演示:

package com.spring_bean.inter;

public interface Store {

}


package com.spring_bean.impl;

import com.spring_bean.inter.Store;

public class StringStore implements Store {

}


package com.spring_bean.service;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.spring_bean.impl.StringStore;
import com.spring_bean.inter.Store;

@Configuration
public class StoreConfig {

	@Bean(name="store")
	public Store getStringStore()
	{
		return new StringStore();
	}
}


package com.spring_bean.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring_bean.inter.Store;
import com.spring_bean.service.StoreConfig;

public class TestSpringBean {

	@Test
	public void testBean()
	{
		//加载配置文件
		//@SuppressWarnings("resource")
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext_Bean.xml");
		
		//初始化加载的Bean
		StoreConfig sc = (StoreConfig)context.getBean("store");
		//Store sc = (Store)context.getBean("stringStore");
		//输出bean的名字
		System.out.println(sc.getClass().getName());
	}
}

配置文件:

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:cache="http://www.springframework.org/schema/cache"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context.xsd  
    http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans.xsd  
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx.xsd  
    http://www.springframework.org/schema/jdbc  
    http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd  
    http://www.springframework.org/schema/cache  
    http://www.springframework.org/schema/cache/spring-cache-3.1.xsd  
    http://www.springframework.org/schema/aop  
    http://www.springframework.org/schema/aop/spring-aop.xsd  
    http://www.springframework.org/schema/util  
    http://www.springframework.org/schema/util/spring-util.xsd">  
	
	 <!-- 开启Spring注解 -->
	<context:annotation-config></context:annotation-config>
	
</beans> 



执行结果:



异常描述:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'getStringStore' is defined
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1168)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:281)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
	at com.spring_bean.test.TestSpringBean.testBean(TestSpringBean.java:21)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

说是这个bean没有被注释。没有动为啥出现这样的情况。根本就没有加载Bean。这个问题有待解决。


























回答: @Bean注解Java Spring框架中的一个注解,用于在@Configuration类中声明一个方法,该方法将返回一个被Spring容器管理的Bean对象。\[1\]相比于其他注册Bean注解@Bean注解的灵活性更高。因为它可以用在方法上,而不仅仅是类上,这意味着你可以在方法中使用条件语句或其他逻辑来动态获取Bean对象,使其能够根据环境的变化而变化。\[2\]此外,@Bean注解还可以用来提供Bean的详细描述,通过使用@Description注解来提供Bean的描述信息,使得对Bean的理解更加清晰。\[3\]总之,@Bean注解Spring框架中用于声明和注册Bean的一种灵活且功能强大的注解。 #### 引用[.reference_title] - *1* [基于Java容器注解@Bean](https://blog.youkuaiyun.com/wu631464569/article/details/51952787)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [对@Bean注解的学习理解(大白话解释)](https://blog.youkuaiyun.com/lzhNox/article/details/127780114)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [spring @Bean注解的使用](https://blog.youkuaiyun.com/weixin_30273763/article/details/97971121)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值