博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring -- 全注解下的IoC(1)
阅读量:4595 次
发布时间:2019-06-09

本文共 2282 字,大约阅读时间需要 7 分钟。

  Spring IoC容器

    1. Spring IoC 容器简介

  • Spring Bean :Spring中每一个需要管理的对象称为Spring Bean(简称 Bean)。
  • Spring IoC容器:管理Bean 的容器。
    • 1. 通过描述管理Bean, 包括发布和获取Bean。
    • 2. 通过描述完成Bean之间的依赖关系。

   2. 通过@Componet 自动的装配你的Bean

     2.1 编写一个简单的User类    

package com.examole.demo2;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;/* @Component 标识这个类将Spring IoC容器扫描装配,user作为Bean的名字注入到IoC中*//* 如果不给括号里的name IoC容器会把类名首字母小写其它不变注作为名称注入IoC容器中 */@Component("user")public class User {    /* @value给下面字段注入值 */    @Value("1")    private Long id;    @Value("user_name_1")    private String user_name;    @Value("note_1")    private String note;    /** Geter And Seter Here**/        }

   2.2 编写一个 AppConfig 配置类

   @Configuration 注解会辨识这是一个配置类

   @ComponentScan 注解会去扫描某一个包下,所有标识有@Component 的类, 创建他们的对象存入Spring IoC容器中

package com.examole.demo2;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.stereotype.Service;@Configuration/* 当我们不给@ComponentScan中标识指定的包时,他会扫描它自所在的包   使用excludeFilters = {@ComponentScan.Filter(classes = {Service.class})} 可以在扫描某一个包时,越过一些特殊的类(如使用@Service 注解的类)*/@ComponentScan(basePackages = {"com.examole.demo2"},excludeFilters = {@ComponentScan.Filter(classes = {Service.class})})//@ComponentScan("com.examole.demo2.*") 扫描指定包下所有的文件//@ComponentScan(backPackagesClasses = {User.class})  扫描指定的类public class AppConfig {}

 

  

  UserService类

package com.examole.demo2;import org.springframework.stereotype.Service;@Servicepublic class UserService {    public void printUser(User user){        System.out.println(user.getId());        System.out.println(user.getUser_name());        System.out.println(user.getNote());    }}

   2.3 验证 

package com.examole.demo2;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Test {    public static void main(String[] args) {        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(User.class);        User user = applicationContext.getBean(User.class);        UserService service = new UserService();        service.printUser(user);    }}

  

  结果

 

转载于:https://www.cnblogs.com/dyf-stu/p/10077213.html

你可能感兴趣的文章
java的Integer与int的比较
查看>>
openstack安装文档
查看>>
正在改变世界的硅谷创业趋势
查看>>
No2_3.接口继承多态_Java学习笔记_多态
查看>>
[转] 体内湿气重怎样祛除
查看>>
C#多线程学习(五) 多线程的自动管理(定时器)
查看>>
第三次作业
查看>>
物体坐标to世界坐标
查看>>
上传图片进行预览
查看>>
Git学习笔记(二)
查看>>
jquery
查看>>
JS打造的跟随鼠标移动的酷炫拓扑图案
查看>>
【MyBatis】MyBatis Tomcat JNDI原理及源码分析
查看>>
Perl模块利用CPAN在线安装自动化
查看>>
[翻译]OAuth入门指南 – 1.概述
查看>>
精通 Windows API 函数、接口、编程实例 --- 卷首语
查看>>
Json.net 常用使用小结
查看>>
<context:component-scan/>和<mvc:annotation-driven/>的区别
查看>>
Android 命名规范 (提高代码可以读性)
查看>>
【转】asp二级联动的数据库版。
查看>>