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("明明");
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App