1. 程式人生 > >spring例項Bean的三種方式_註解

spring例項Bean的三種方式_註解

第一步:實體

//compnent為任意註解

package it.heima.domain;
import org.springframework.stereotype.Component;

@Component("product")
public class Product {

}

第二步:配置(自動掃描包)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    //自動掃描包
    <context:component-scan base-package="it.heima.domain"/>

</beans>

第三步:測試

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ProductTest {
    @Test
    public void test(){
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext_annotation.xml");
        Product product = applicationContext.getBean("product", Product.class);
        System.out.println(product);
    }

}