上图中的配置和下面的bean的配置效果是一样的:
@Bean之自定义Bean name:
使用初始化和销毁方法
package com.wuyonghu.resources; public interface Store { } package com.wuyonghu.resources; public class StringStore implements Store{ } package com.wuyonghu.resources; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class StoreConfig { @Bean public Store getStringStore(){ return new StringStore(); } }测试代码:
@Test public void testHello8() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); //在@Bean注解没有指定名称的时候,默认的名称是@Bean注解的方法名。可以在@Bean中使用name属性指定名称 Store resources = (Store) context.getBean("getStringStore"); System.out.println(resources.getClass().getName()); }