1. 程式人生 > >Spring Boot-04Spring Boot基礎-使用註解裝配bean

Spring Boot-04Spring Boot基礎-使用註解裝配bean

文章目錄

概述

Spring Boot主要是通過註解來裝配 Bean 到 Spring IoC 容器中,使用註解裝配Bean就不得不提AnnotationConfigApp licationContext,很顯然它是一個基於註解的 IoC 容器。

示例

POJO類

package com.artisan.springbootmaster.pojo;

public class Artisan {

    public String name;
    public int age;

   	// setter/getter
}


package com.artisan.springbootmaster;
import com.artisan.springbootmaster.pojo.Artisan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean(name = "artisan") public Artisan initArtisan(){ Artisan artisan = new Artisan
(); artisan.setName("小工匠"); artisan.setAge(20); return artisan; } }
package com.artisan.springbootmaster;

import com.artisan.springbootmaster.pojo.Artisan;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class LoadTest { public static void main(String[] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); //Artisan artisan = applicationContext.getBean(Artisan.class); Artisan artisan = (Artisan) applicationContext.getBean("artisan"); System.out.println(artisan.getName() + " || " + artisan.getAge()); } }