Spring注解驱动开发——组件注册 @Configuration
一 @Bean
1)方法名作为容器bean的id
1 代码
package com.mongoubiubiu.conf; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.ComponentScans; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.Import; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import com.mongoubiubiu.bean.Black; import com.mongoubiubiu.bean.ColorFactoryBean; import com.mongoubiubiu.bean.Person; import com.mongoubiubiu.bean.Red; import com.mongoubiubiu.bean.Yellow; import com.mongoubiubiu.condition.MyInportSelect; import com.mongoubiubiu.dao.UserDao; import com.mongoubiubiu.service.UserService; //配置类==配置文件 @Configuration //告诉spring 这是一个配置类 public class MyConf { //给容器中注册一个bean; 类型为返回值的类型 id默认是用方法名做为id @Bean public Person person222(){ return new Person("王五", 19); } }
2 测试
package com.mongoubiubiu; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.mongoubiubiu.bean.Person; import com.mongoubiubiu.conf.MyConf; public class MainTest { public static void main(String[] args) { ApplicationContext applica= new AnnotationConfigApplicationContext(MyConf.class); String[] applicastr= applica.getBeanNamesForType(Person.class); for (String string : applicastr) { System.out.println(string); } } }
可以发现方法名作为容器中bean 的id
2)自定义bean的id
1 代码
//给容器中注册一个bean; 类型为返回值的类型 id默认是用方法名做为id @Bean("xixi") public Person person222(){ return new Person("王五", 19); }
2 测试