Spring注解介绍

本文介绍了在Spring框架中如何使用注解如@Component、@Repository、@Service和@Controller来替代XML配置文件,以及@Autowired和@Resource注解的使用,展示了在Java三层架构中如何利用Spring的bean扫描进行开发。
摘要由CSDN通过智能技术生成

在Spring框架中尽管使用XML配置文件可以很简单地装配Bean,但如果应用中有大量Bean需要进行装配时,会导致XML配置文件过于庞大,不方便后期的升级维护。因此更多时候推荐开发者使用注解的方式去装配Bean.

声明bean注解:

注解说明
==@Component==该注解用于描述 Spring 中的 Bean,它是一个泛化的概念,仅仅表示容器中的一个组件(Bean),并且可以作用在应用的任何层次,例如 Service 层、Dao 层等。 使用时只需将该注解标注在相应类上即可。
@Repository该注解用于将数据访问层(Dao 层)的类标识为 Spring 中的 Bean,其功能与 @Component 相同。
@Service该注解通常作用在业务层(Service 层),用于将业务层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。
@Controller该注解通常作用在控制层(如SpringMVC 的 Controller),用于将控制层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。

注入Bean的注解:

注解说明
==@Autowirted==该注解可以对类的成员变量、方法以及构造方法进行标注,完成自动装配工作。
@Resource该注解与@Autowirted功能一样,区别在于该注解默认按照Bean名称装配注入,只有当找不到与名称匹配的Bean时才会按照类型装配注入;而@Autowirted默认按照Bean类型进行装配,如果按照名称进行装配注入,则需要结合@Qualifier进行使用。
@Qualifier该注解与@Autowrited注解配合使用。当@Autowrited注解需要按照名称进行注入时,则需要结合该注解一起使用,Bean的名称需要由@Qualifier注解参数决定。

注:@Resource注解由两个属性:name和type。name属性指定Bean的实例名称,即按照名称来注入;type属性指定Bean类型,即按照Bean的类型进行装配。

==下面将模拟Java三层架构进行使用spring的bean扫描进行开发==

持久层:

 

public interface TestDao { void save(); }

实现类:

 

@Component /* * 相当于在applicationContext.xml文件中: * <bean id="testDaoImpl" class="com.itFuml.annotation.TestDaoImpl"/>*/ public class TestDaoImpl implements TestDao{ @Override public void save() { System.out.println("Hello Spring save..."); } }

服务层:

 

public interface TestService { void save(); }

实现类:

 

@Service public class TestServiceImpl implements TestService{ @Autowired /* * 注入资源属性,在applicationContext.xml文件中: * <!-- <bean id="testServiceImpl" class="com.itFuml.annotation.TestServiceImpl">--> <!-- <property name="testDao" ref="testDaoImpl"/>--> <!-- </bean>--> * */ private TestDao testDao; @Override public void save() { testDao.save(); } }

控制层:

 

@Controller public class TestController { @Autowired private TestService testService; public void save(){ testService.save(); System.out.println("Controller..."); } }

测试类:

 

public class TestService { public static void main(String[] args) { ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml"); TestController testController = context.getBean("testController", TestController.class); testController.save(); } }

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值