注解实现自动装配
- 先设置好配置文件
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!-- 使用注解必须写-->
<context:annotation-config/>
</beans>
@Resource and @Autowire的区别
- 都是实现自动装配,都可以放在字段属性上
- @Autowire 通过byType的方式实现,如果有多个bean的type相同但是名字不同且名字
和对象的属性名字也不同,可以在@Autowire下使用 @Qualifier(value = “对象名字”)来找到bean - @Resource 默认通过byName的方式去实现,如果找不到名字,则通过byType的方式去实现,如果都
找不到,就报错
使用注解开发
- 举例子
<!-- 制定要扫描的包 该包下的注解就会生效-->
<context:component-scan base-package="com.xu.pojo"/>
- pojo下有个User类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//component组件 配置文件会扫描这里
@Component
public class User {
@Value("xu")
public String name;
}
@Component有几个衍生注解,在web开发中,会按mvc三层架构分层
- dao @Repository
- service @Service
- controller @Controller
这四个注解的功能是一样的,都是代表某个类将注册到bean中,装配bean
xml 用来管理bean 注解完成属性注入spring新特性可以完全不适用xml来实现注入
- User类在pojo包下
package com.xu.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
public class User {
@Value("xuqq")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
= 配置类xuConfig
package com.xu.config;
import com.xu.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//这个也会被spring托管 ,因为也属于@Component
//@Configuration代表一个配置类,就和applicationContext.xml作用相同
@Configuration
@ComponentScan("com.xu.pojo")
public class xuConfig {
//注册一个bean 就相当于之前bean标签
//方法名字就相当于id
//方法的返回值就相当于bean标签中的class属性
@Bean
public User getUser(){
//返回要注入的对象
return new User();
}
}