package com.springboot.chapter3.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import lombok.Data; @Component("user") public @Data class User { @Value("1") private Long id; @Value("user_name_1") private String userName; @Value("note_1") private String note; }
代碼清單3-6 Appconfig.java
package com.springboot.chapter3.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan public class Appconfig { }
代碼清單3-7 IoCTest.java
package com.springboot.chapter3.config; import org.apache.log4j.Logger; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class IoCTest { private static Logger log = Logger.getLogger(IoCTest.class); public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(Appconfig.class); User user = ctx.getBean(User.class); log.info(user); } }
執行結果

把User.java 移到 package com.spring.chapter3.pojo
package com.springboot.chapter3.pojo; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import lombok.Data; @Component("user") public @Data class User { @Value("1") private Long id; @Value("user_name_1") private String userName; @Value("note_1") private String note; }
改變componentScan的位置
package com.springboot.chapter3.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration //可以wildcat //@ComponentScan("com.springboot.chapter3.*") @ComponentScan("com.springboot.chapter3.pojo") public class Appconfig { }