@Configuration&@Bean
微信公众号:程序yuan
如果需要spring注解视频,请到公众号评论留言。源码,视频全部奉上!
当前springboot真是老火了,所以非让自己学一把,但是学了前面一部分基础之后,发现springboot都是注释,虽然都是spring的或是基于spring的,可之前学spring的时候都是用的xml方式,所以对spring注释比较陌生,无奈,只能回头看看spring注解版了。(陆续更新,欢迎关注。。。)
使用@Configuration指定一个配置类 ==> xml文件
使用@Bean类注入一个bean ==><bean></bean>
第一种:使用XML的方式注入Bean
Person.java
package com.ooyhao.bean;
import java.io.Serializable;
/**
* @author ooyhao
*/
public class Person implements Serializable {
private String name;
private Integer age;
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
//省略Getter/Setter/toString()
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.ooyhao.bean.Person">
<property name="name" value="张三"></property>
<property name="age" value="18"></property>
</bean>
</beans>
测试文件:
@Test
public void TestXML() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Person person = (Person) context.getBean("person");
System.out.println(person);
}
第二种:使用注解与配置类的方式
Config.java
package com.ooyhao.config;
import com.ooyhao.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author ooyhao
*/
//配置类==配置文件
@Configuration //告诉Spring这是一个配置类
public class MainConfig {
// 给容器中注册一个Bean,类型就是返回值的类型,id默认是用方法名作为id、
@Bean("person")
public Person person01(){
return new Person("李四",20);
}
}
测试文件:
@Test
public void testConfig(){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
Person person = context.getBean(Person.class);
System.out.println(person);
String[] names = context.getBeanNamesForType(Person.class);
System.out.println(Arrays.toString(names));
}
总结:
1.MainConfig.java.相当于beans.xml。(需要使用@Configuration注解指明)
2.@Bean所标注的方法,相当于<bean></bean>.方法返回值的类型就是Bean的类型。方法名默认就是bean的id名。
但是可以在@Bean注解的value或name属性进行修改。修改后id名就变为@Bean标注的了。
String[] names = context.getBeanNamesForType(Person.class);
System.out.println(Arrays.toString(names));//结果如上:person。而不是person01
注意:不同的spring版本的@Bean可使用的属性不同。这里的4.3.12有name和value。而后面的只有name.
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {
@AliasFor("name")
String[] value() default {};
@AliasFor("value")
String[] name() default {};
Autowire autowire() default Autowire.NO;
String initMethod() default "";
String destroyMethod() default "(inferred)";
}
------------------------------------------------
------------------------------------------------