使用注需要配置注解的支持
applicationContext.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"
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.peng.pojo"/>
<!--开启注解驱动支持-->
<context:annotation-config/>
<bean id="cat" class="com.peng.pojo.Cat"/>
<bean id="dog" class="com.peng.pojo.Dog"/>
<bean id="people" class="com.peng.pojo.People"/>
</beans>
pom.xml
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.19</version>
</dependency>
@Autowired
bean文件按上方配置,然后在属性上面写注解,就可以实现自动装配
@Qualifier
通过id指定bean进行装配
当@Autowired自动装配比较复杂时可以使用@Qualifier组合装配
@Resource注解
public class People {
private String name;
@Resource
private Cat cat;
@Resource(name="dog3")
private Dog dog;
}
@Resource注解和@Autowired的区别
- 都是用来自动装配的,都可以放在属性字段上面
- @Autowired通过byType 的方式实现,而且逼需要求这个对象存在
【常用】
- @Resource默认是通过byName的方式来实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下会报错
【常用】
- 执行顺序不同@Autowired通过byType的方式实现。@Resource默认通过byName的方式实现.
@Component
等价于
<bean id="user" class="com.peng.pojo.User"/>
@Value("值")
等价于:
<bean id="user" class="com.peng.pojo.User">
<property name="name" value="值"/>
</bean>
@Repository
在dao层使用
@Controller
在controller层使用
@Service
在service层使用
通过纯java的方式也可以实现
PengConfig类.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import peng.pojo.User;
@Configuration
public class PengConfig {
@Bean
public User getUser(){
return new User();
}
}
实体类User
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("鹏哥")
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
测试类
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import peng.controller.PengConfig;
import peng.pojo.User;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(PengConfig.class);
//这里的对象跟Spring的对象不一样
User user= (User) context.getBean("getUser");
System.out.println(user.getName());
}
}