static 使用

博客展示了Java代码,定义了名为Chinese的类。该类包含构造器、静态变量、实例变量,还有判断字符串是否为空的静态方法和显示对象创建数量的静态方法,体现了Java面向对象编程的特性。

package New_Dao;

public class Chinese {
//记录了构造器调用次数
public Chinese(){
Chinese.count++;
}
// public static String country; //定义静态变量作用全局
static String country; //定义静态变量作用全局 //常量 类变量
String name ;
int age;
public static int count; //计数
public static boolean StrisNull(String str) {
if (str != null && !str.equals("")) {
return true; //判断是否为字符串
}
return false;
}
public static void showCount (){
System.out.println(“总共new了”+Chinese.count + “个对象”);
}

public static void main(String[] args) {
    Chinese.country= "中国"; // 使用静态全局变量
    Chinese ch = new Chinese();
    Chinese ch1 = new Chinese();
    showCount();
    Chinese ch2 = new Chinese();
    Chinese ch3 = new Chinese();
    showCount();
    Chinese ch4 = new Chinese();
    ch.age=18;
    ch.name="root";

    String s = "";
    System.out.println(StrisNull(s));
}

}

static修饰的情况下,不能直接在static字段上使用@Value注解,因为@Value注解是通过访问Spring容器中的上下文来解析属性值并注入到目标字段中的,而static字段不属于对象实例,无法通过实例访问容器,所以在静态字段上直接使用@Value注解是无效的[^1]。 若要在static修饰的情况下使用@Value,可以借助非静态的setter方法来实现。示例代码如下: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class StaticValueExample { private static String staticValue; @Value("${your.property.key}") public void setStaticValue(String value) { staticValue = value; } public static String getStaticValue() { return staticValue; } } ``` 在使用时需要注意以下几点: - 避免直接在static字段上使用@Value注解,否则无法注入值。 - 确保类被Spring管理,即类上要添加@Component、@Service等注解,这样Spring才能扫描到该类并进行依赖注入。 - 注意初始化顺序陷阱,静态字段在Spring启动完成前访问会得到null。可以使用@PostConstruct注解来确保在静态字段完成注入后再进行访问,示例如下: ```java import javax.annotation.PostConstruct; import org.springframework.stereotype.Component; @Component public class StaticValueExample { private static String staticValue; public static String getStaticValue() { return staticValue; } @Value("${your.property.key}") public void setStaticValue(String value) { staticValue = value; } @PostConstruct public void init() { // 此时静态字段已完成注入 System.out.println(getStaticValue()); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值