pom.xml
4.0.0 org.springframework.samples chapter3 0.0.1-SNAPSHOT 1.6 UTF-8 UTF-8 3.2.3.RELEASE 1.0.13 1.7.5 org.springframework spring-context ${spring-framework.version} org.springframework spring-tx ${spring-framework.version} org.slf4j slf4j-api ${slf4j.version} compile ch.qos.logback logback-classic ${logback.version} runtime org.projectlombok lombok 1.16.10 provided log4j log4j 1.2.17
代碼清單3-2 User.java
package com.springboot.chapter3.pojo;
import lombok.Data;
public @Data class User {
private Long id;
private String userName;
private String note;
}
代碼清單3-3 Appconfig.java
package com.springboot.chapter3.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.springboot.chapter3.pojo.User;
@Configuration
public class Appconfig {
@Bean(name = "user")
public User initUser() {
User user = new User();
user.setId(1L);
user.setUserName("user_name_1");
user.setNote("note_1");
return user;
}
}
代碼清單3-4 IoCTest.java
package com.springboot.chapter3.config;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.springboot.chapter3.pojo.User;
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);
}
}
log4j.properties
#定義 Root Logger 的等級為 INFO,且為其指定一個 appender 名為 rootAppender.
log4j.rootLogger=INFO, console
#指定 console 的類型.
log4j.appender.console=org.apache.log4j.ConsoleAppender
#指定 console 的 Layout.
log4j.appender.console.layout=org.apache.log4j.PatternLayout
#log4j.appender.console.Target=System.out
#指定 console Layout 的輸出格式.
log4j.appender.console.layout.ConversionPattern=%5p [%d{yyyy-MM-ddHH:mm:ss}]-[%c{1}:%L][%x] %m%n
Eclipse 看 .properties 亂碼要改

執行結果
