专注于分布式,性能优化,代码之美

Java学习记录

1.工具类SpringUtils 获取spring容器中的bean


public static <T> T getBean(String name, Class<T> type) {
return applicationContext.getBean(name, type);
}
StringUtils.getBean(name, type);


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;

@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
if (SpringUtils.applicationContext == null) {
SpringUtils.applicationContext = arg0;
}
}

// 获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}

// 通过name获取 Bean.
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}

// 通过class获取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}

// 通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}

 

2.@SuppressWarnings该批注的作用是给编译器一条指令,告诉它对被批注的代码元素内部的某些警告保持静默。
作用:
告诉编译器忽略指定的警告,不用在编译完成后出现警告信息。

 

3.java使用 org.springframework.beans.BeanUtils 工具类,把一个bean的属性值复制到另一个bean中,
前提是这个复制的bean的字段要完全包含在被复制的bean中


4.在java中,为了判断查询的类对象是否存在,采用此方法:

public ShopHomeView findByOwnerIds(String ownerId) {

Optional<ShopHomeView> view = shopHomeViewRepository.findByOwnerId(ownerId);
if(view.isPresent()) {
return view.get();
}else {
return null;
}
}

 

5.isPresent(),判断对象是否存在,
一般与.get()方法合用,当view存在时,view.isPresent()值为true,通过get()方法返回对象。
ifPresent 用于对过滤出的数据如果存在。如果经过过滤条件后,有数据的话就可以进行修改。
Optional<A> firstA= AList.stream()
.filter(a -> "小明".equals(a.getUserName()))
.findFirst()
.ifPresent(a -> {
a.setUserName("明明");

 

posted on 2022-05-09 17:03  xiaohouye  阅读(39)  评论(0编辑  收藏  举报

导航

今日之劳累是为了铸造明日之辉煌,不管年龄多少,都无法阻挡我对软件艺术的追求!