买源码的网站,公司官网格式设计,绵阳网站建设怎么做,网站客户运营小王学习录 前言基于注解存储对象Controller (控制器存储)Service (服务存储)Repository (仓库存储)Component (组件存储)Configuration (配置存储)Bean(方法注解) 前言
上一篇文章中已经介绍了在Spring中存储Bean和取Bean的方法. 而在 Spring 中想要更简单的存储和读取对象的… 小王学习录 前言基于注解存储对象Controller (控制器存储)Service (服务存储)Repository (仓库存储)Component (组件存储)Configuration (配置存储)Bean(方法注解) 前言
上一篇文章中已经介绍了在Spring中存储Bean和取Bean的方法. 而在 Spring 中想要更简单的存储和读取对象的核⼼是使⽤注解. 这篇文章介绍如何基于注解存储对象
基于注解存储对象
基于注解存储对象第一步仍然是先修改spring配置文件. 加入代码
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsdcontext:component-scan base-packagecom.annotation/context:component-scan
/beans其中代码context:component-scan base-packagecom.annotation/context:component-scan是在注册要扫描的包, spring启动后, 会自动在指定的包(此处是com.annotation)下扫描, 找到加了注解的类, 然后创建Bean对象并存储到spring容器中. 接下来介绍存储Bean对象的注解.
用于存储Bean对象的注解有五大类注解和一个方法注解. 五大类注解分别是: Controller, Service, Repository, Component, Configuration 方法注解: Bean Controller (控制器存储)
Controller
public class UseController {public void print(){System.out.println(do_useController);}
}Service (服务存储)
Service
public class UseService {public void print(){System.out.println(do_useService);}
}Repository (仓库存储)
Repository
public class UseRepository {public void print(){System.out.println(do_useRepository);}
}Component (组件存储)
Component
public class UseComponent {public void print(){System.out.println(do_useComponent);}
}
Configuration (配置存储)
Configuration
public class UseConfiguration {public void print(){System.out.println(do_useConfiguration);}
} 在五大类注解中, Controller, Service, Repository, configuration都是Component的子类.
对于五大类注解的Bean对象命名规则, 观察底层实现源码之后发现. 如果类名前两位都是大写, 则Bean对象名与类名一致. 如果类名第一位大写, 第二位小写, 则Bean对象名是类名第一位小写, 其他位不变. Bean(方法注解)
Bean要搭配类注解一起使用, 使用 Bean 注解标记的方法将会被Spring容器注册为一个Bean, 并且该Bean的实例将由该方法返回。
Component
public class UserBeans {Beanpublic User user1(){User user new User();user.setId(1);user.setName(zhangsan);user.setPassword(lisi);return user;}
}User user applicationContext.getBean(user1, User.class);System.out.println(user.getPassword());Bean注解中可以用name或value指定Bean的对象名, 如果没有指定默认对象名默认为方法名. 上面的例子中没有指定对象名, 下面写一个指定对象名的例子.
Component
public class UserBeans {Bean(name {user0, user})public User user1(){User user new User();user.setId(1);user.setName(zhangsan);user.setPassword(lisi);return user;}
}User user applicationContext.getBean(user0, User.class);System.out.println(user.getPassword());上面的这个例子在获取Bean对象时, 可以用user0, 也可以用user, 但是默认的方法名(user1)不能使用.