spring用注解“简化applicationContext.xml配置”,为简化spring复杂的配置,spring支持使用注解来代替xml配置。开启spring注解的步骤如下:
1、开启组件扫描,这样加了注解的类才会被识别出来。spring才能去解析其中的注解,即要在spring的applicationContext.xml配置文件中声明:
<content-component-scan base-package="com.package"/>
2、bean注解@Component @Controller@Service @Respository代替配置文件xml中声明的bean。这4个注解都可以起到类似xml配置文件中bean标签的作用,spring将加了注解类的对象放入到spring容器中,默认为singleton。
(1)、如果是Controller类,通常使用@Controller注解。
(2)、如果是Service类,通常使用@Service注解。
(3)、如果是Dao类,通常使用@Repository注解。
(4)、如果是其他类,可以使用@Component注解。
如xml中bean的声明:
<bean id="studentDao" class="com.package.dao.impl.StudentDaoImpl" ></bean>
用注解的方式实现:在StudentDaoImpl类文件头声明@Repository即可
@Repository
public class StudentDaoImpl implements StudentDao {
...
...
...
}
3、bean属性注解@Value @AutoWired @Qualifier
(1)、@Value注解:实现 简单属性 也即基本数据类型 属性的注解。如:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
public class Student {
@Value("1")
private int id;
@Value("张三")
private String name;
@Value("22")
private int age;
}
上面的@value注解 等同于 xml中bean 的 property 的 value的声明。
<bean class="com.package.domain.Student" id="student">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="22"></property>
</bean>
(2)、@AutoWired注解:spring会给加了 该注解的属性 自动注入数据类型 相同的对象。如:
@Service("studentService")
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
}
(3)、@Qualifier注解,但@Qualifier不可单独使用。
如果一个接口 有多个 实现类,那么需要@Autowired+@Qualifier一起明确指定需要注入的属性对象。
如:
@Service("studentService")
public class StudentServiceImpl implements StudentService {
@Autowired
@Qualifier("studentDao") 或者
@Qualifier("studentDao2")
private StudentDao studentDao;
}
@Repository("studentDao")
public class StudentDaoImpl implements StudentDao {
...
...
...
}
@Repository("studentDao2")
public class StudentDaoImpl2 implements StudentDao {
...
...
...
}
总结:虽然用上面的注解大大简化了xml的配置,但项目中还是没离开spring的xml配置文件。