1.注解方式入门
传统的Spring做法是使用.xml
文件来对bean进行注入或者是配置aop、事物,这么做有两个缺点:
- 如果所有的内容都配置在
.xml
文件中,那么.xml
文件将会十分庞大;如果按需求分开.xml
文件,那么.xml
文件又会非常多。总之这将导致配置文件的可读性与可维护性变得很低。 - 在开发中在
.java
文件和.xml
文件之间不断切换,是一件麻烦的事,同时这种思维上的不连贯也会降低开发的效率。
为了解决这两个问题,Spring引入了注解,通过"@XXX"
的方式,让注解与Java Bean紧密结合,既大大减少了配置文件的体积,又增加了Java Bean的可读性与内聚性。
前面我们使用非注解的方式,实现Spring程序。
下面我们使用注解方式实现,
注解开发Spring
注解:
- @Component : 组件 bean
等价于:<bean id="user" class="or.xiao.dao.User"/>
- @Controller :web层
- @Service : service层
- @Repository :dao层
代码:
1.使用注解开发需要导入spring的一系列包,包括aop包。
2.需要在配置文件中增加命名空间的约束,context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
3.开启spring的注解功能,
扫描指定位置下的包。
<!--自动扫描指定包下的注解-->
<context:component-scan base-package="org.xiao.dao"/>
4.编写代码
package org.xiao.dao;
import org.springframework.stereotype.Component;
//等价于:<bean id="user" class="or.xiao.dao.User"/>
/*
@Component : 组件 bean
@Controller :web层
@Service : service层
@Repository :dao层
*/
@Component("user")
public class User {
public String name = "小仙女1";
}
5.测试类
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) context.getBean("user");
System.out.println(user.name);
}
2. IoC注入
-
可以不用提供set方法,直接在属性名上添加一个@Value(值)。
@Controller("user2") public class User2 { // <bean class="org.xiao.dao.User2" id="user2"> // <property name="name" value="小仙女2"/> // </bean> private String name; public String getName() { return name; } @Value("小仙女2") public void setName(String name) { this.name = name; } }
-
测试类
@Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User2 user = (User2) context.getBean("user2"); System.out.println(user.getName()); //System.out.println(user.dog.name); }
3. 注解和XML的对比
-
xml可以适用任何场景,结构清晰,推荐使用
-
注解不是自己提供的类,存在局限性;好处为简化xml,开发简单,方便。
-
xml和注解的最佳实践:
xml管理bean。
注解完成属性的注入。