@Component
该注解是组件的意思,放在类上,说明这个类被Spring管理了,也就是bean,该注解等价于我们的配置文件 <bean id="user" class="com.zhiying.pojo.User"/>
这里依然是用案例来进行描述,首先是User实体类
package com.zhiying.pojo;
import org.springframework.stereotype.Component;
@Component
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
然后是我们的配置文件,这里的配置文件用来声明一下哪个包下用了注解,用于扫描该包
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.zhiying.pojo"/>
</beans>
然后是测试
import com.zhiying.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) context.getBean("user");
user.setName("hzy");
System.out.println(user.getName());
}
}
这样是可以,我们发现value值的设置很不方便。
@Value
在配置文件中是<property name="name" value="hzy"/>,这里我们用@Value
只需修改这里修改User类如下
package com.zhiying.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("hzy")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
测试类
import com.zhiying.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) context.getBean("user");
System.out.println(user.getName());
}
}
衍生注解
在MVC三层架构中,Dao、Service和Controller中分别有自己的注解,其是等价于Component,都是将某个类装配到Spring中装配bean
Dao:@Respository
Service:@Service
Controller:@Controller
自动装配的注解
@Autowired和@Resource在上一篇博客有详细介绍Spring自动装配Bean_贺贺学编程的博客-CSDN博客
作用域@Scope
可以在User类上设置其为单例:@Scope("singleton"),也可以设置为原型@Scope("prototype")
这里的单例和原型在之前也详细讲过Spring中Bean的作用域_贺贺学编程的博客-CSDN博客