国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > Java > 正文

利用注解配置Spring容器的方法

2024-07-13 10:14:38
字體:
供稿:網(wǎng)友

本文介紹了利用注解配置Spring容器的方法,分享給大家,具體如下:

@Configuration標(biāo)注在類上,相當(dāng)于將該類作為spring的xml的標(biāo)簽

@Configurationpublic class SpringConfiguration { public SpringConfiguration() {  System.out.println("初始化Spring容器"); }}

主函數(shù)進(jìn)行測試

public class Main { public static void main(String[] args) {  ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class); }}

利用注解AnnotationConfigApplicationContext加載ApplicationContext

運行結(jié)果如下

信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2e5d6d97: startup date [Sat Dec 09 11:29:51 CST 2017]; root of context hierarchy
初始化Spring容器

利用@Bean向容器中添加bean實例

public class User { private String username; private int age; public User(String username, int age) {  this.username = username;  this.age = age; } public void init(){  System.out.println("初始化User..."); } public void say() {  System.out.println(String.format("Hello,my name is %s,I am %d years old ", username, age)); } public void destory(){  System.out.println("銷毀User ..."); }}
@Configurationpublic class SpringConfiguration { public SpringConfiguration() {  System.out.println("初始化Spring容器"); } //@Bean注解注冊bean,同時制定初始化和銷毀的方法 @Bean(name = "user", initMethod = "init", destroyMethod = "destory") @Scope("prototype") public User getUser() {  return new User("tom", 20); }}

@Bean注解在返回實例的方法上,如果沒有指定bean的名字,則默認(rèn)與標(biāo)注的方法名稱相同

@Bean注解默認(rèn)作用域為單例的Singleton作用域

利用@ComponentScan添加自動掃描@Service,@Ripository,@Controller,@Component注解

@Componentpublic class Cat { public Cat() { } public void say() {  System.out.println("I am a cat" ); }}
@Configuration@ComponentScan(basePackages = "com.spring.annotation.ioc")public class SpringConfiguration { public SpringConfiguration() {  System.out.println("初始化Spring容器"); } //@Bean注解注冊bean,同時制定初始化和銷毀的方法 @Bean(name = "user", initMethod = "init", destroyMethod = "destory") @Scope("prototype") public User getUser() {  return new User("tom", 20); }}

利用basePackages掃描包配置路徑

運行結(jié)果如下

初始化Spring容器初始化User...Hello,my name is tom,I am 20 years old I am a cat

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。


注:相關(guān)教程知識閱讀請移步到JAVA教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 咸阳市| 元朗区| 宁河县| 故城县| 临泉县| 女性| 洛南县| 丰宁| 宿州市| 滕州市| 会理县| 通道| 天祝| 静海县| 天全县| 麻栗坡县| 昭苏县| 马公市| 曲水县| 浙江省| 城市| 岐山县| 湘潭市| 穆棱市| 八宿县| 山阳县| 贺兰县| 南京市| 天全县| 莱芜市| 綦江县| 九寨沟县| 延边| 汝南县| 瑞金市| 辽源市| 淅川县| 东兴市| 博乐市| 邢台市| 连云港市|