前言
接上节我们使用配置文件进行了显示的配置,这节我们学习隐式的自动装配bean【重要】!
一、隐式的自动装配bean【重要】
就是使用注解进行配置,Spring2.5就支持注解开发了!!!
使用注解开发时需注意:
- 需要导入context约束
xmlns:context=“http://www.springframework.org/schema/context” http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd - 指定要扫描的包,这个包下的注解就会生效
<context:component-scan base-package="com.shan.pojo"/>
<context:annotation-config/>
- @Component //等价于配置bean
<bean id="user" class="com.shan.pojo.User"/>
- @Value(“小黑神”) //等价于配置属性
<property name="name" value="小黑神"></property>`
并且@Value放在set方法上也可以同样赋值
二、使用步骤
1.需要的实体类
package com.shan.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class User {
@Value("小黑神")
private String name;
public String getName() {
return name;
}
//@Value("小黑神")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
2.配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--先导入context约束,再配置注解的支持-->
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.shan.pojo"/>
<context:annotation-config/>
</beans>
3.测试类
import com.shan.pojo.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void testUser(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = context.getBean("user", User.class);
System.out.println(user);
}
}
测试结果:User{name=‘小黑神’}
说明自动装配成功装入了Bean!
总结
使用注解开发还是比较懒汉的,只要明白每一个注解是放在哪,有什么作用就行!
作者有话说
博客创作不易,希望看到这里的读者动动你的小手点个赞,如果喜欢的小伙伴可以一键三连,作者大大在这里给大家谢谢了。