Spring-IOC-@Value和@PropertySource用法

1、Book.java

  • @PropertySource(value="classpath:配置文件地址") 替代 
  • @Value("${book.bid}")

    @Value("${book.bname}")

    @Value("${book.price}")

               

               

               

package com.atguigu.ioc;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Data
@Component
@PropertySource(value = "classpath:book.properties", encoding = "UTF-8")
public class Book {
    @Value("${book.bid}")
    private Integer bid;
    @Value("${book.bname}")
    private String bname;
    @Value("${book.price}")
    private Integer price;
}

2、book.properties

book.bid=1
book.bname=Java入门经典
book.price=99

3、MySpringConfiguration.java

  • @ComponentScan(basePackages={"包","包"}) 替代
package com.atguigu.ioc;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
public class MySpringConfiguration {
}

4、BookTest.java

package com.atguigu.ioc;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class BookTest {

    private BeanFactory beanFactory;
    @BeforeEach
    public void setup() {
        beanFactory = new AnnotationConfigApplicationContext(MySpringConfiguration.class);
    }
    @Test
    public void test() {
        System.out.println(beanFactory.getBean(Book.class));
    }
}
//Book(bid=1, bname=Java入门经典, price=99)

Spring-IOC-@Value和@PropertySource用法_第1张图片

 5、父工程pom.xml

    pom
    
        pro04-spring-ioc-xml
        pro00-spring-handwrite
        pro05-spring-ioc-annotation
    

    
        17
        17
        UTF-8
        6.0.6
        5.3.1
        1.18.20
    

    
        
            
                org.springframework
                spring-context
                ${spring.version}
            

            
                org.junit.jupiter
                junit-jupiter-api
                ${junit.version}
                test
            
            
                org.projectlombok
                lombok
                ${lombok.version}
            
        
    

6、子工程pom.xml 

    
        com.atguigu
        pro-ssm
        1.0-SNAPSHOT
    

    pro05-spring-ioc-annotation

    
        
            org.springframework
            spring-context
        
        
            org.junit.jupiter
            junit-jupiter-api
        
        
            org.projectlombok
            lombok
        
    

你可能感兴趣的:(#,Spring,Framework,spring,java,Value,PropertySource,Component,ComponentScan,BeforeEach)