“@Value 用法”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) |
||
第25行: | 第25行: | ||
@PropertySource("classpath:spring.properties") | @PropertySource("classpath:spring.properties") | ||
public class AppConfig { | public class AppConfig { | ||
+ | |||
+ | } | ||
+ | </syntaxhighlight>spring.properties<syntaxhighlight lang="properties"> | ||
+ | name=zhangsan | ||
+ | </syntaxhighlight>Test.java<syntaxhighlight lang="java"> | ||
+ | package io.github.jihch; | ||
+ | |||
+ | import org.springframework.context.annotation.AnnotationConfigApplicationContext; | ||
+ | |||
+ | import io.github.jihch.service.UserService; | ||
+ | |||
+ | public class Test { | ||
+ | |||
+ | public static void main(String[] args) { | ||
+ | |||
+ | AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class); | ||
+ | |||
+ | UserService userService = applicationContext.getBean("userService", UserService.class); | ||
+ | |||
+ | userService.test(); | ||
+ | |||
+ | } | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> |
2024年7月23日 (二) 12:35的版本
UserService.java
package io.github.jihch.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class UserService {
@Value("${name}")
private String test;
public void test() {
System.out.println(test);
}
}
AppConfig.java
package io.github.jihch;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
@ComponentScan("io.github.jihch")
@PropertySource("classpath:spring.properties")
public class AppConfig {
}
spring.properties
name=zhangsan
Test.java
package io.github.jihch;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import io.github.jihch.service.UserService;
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = applicationContext.getBean("userService", UserService.class);
userService.test();
}
}