• 作者:Cxxxd
  • 分类: java

定义bean:

 

 

 纯注解开发模式:

用SpringConfig类来代替applicationContext.xml配置文件,利用注解@configuration代表了xml里的基本配置,在SpringConfig类中再加一个注解@ComponentScan("指定包名")替换配置文件的扫描,

加载Spring配置类初始化Spring容器需要更换如下:
//AnnotationConfigApplicationContext加载Spring配置类初始化Spring容器
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);加载配置类

 

 

使用@Scope定义bean作用范围

  @Scope("singleton")表示单例

  @Scope("prototype")表示非单例

@PostConstruct设置bean的初始化方法
@PostConstruct
@PreDestroy设置bean的销毁方法
@PreDestroy


@Autowired替换set方法做装配

 

 

 

 

 

 

 

使用@Value实现注入

1.简单类型:@Value("值")

2.如果使用@Value获取properties配置文件里的值,则需要在SpringConfig类中加个@PropertySource({"配置文件名"}),然后在@Value()输入${变量名}即@Value(${变量名})

 

 

 

第三方管理bean

新建一个JdbcConfig类存放第三方bean

 

 

然后

 

 

简单类型用成员变量

 

 

引用类型用方法形参

 

 

 

 

Spring整合Junit

@RunWith设置专用的类运行器

@ContextConfiguration指定spring的上下文配置类

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 


 

 

 


 

转载自: https://www.cnblogs.com/Cxxxd/p/16699692.html