小编chr*_*ke-的帖子

为什么我的Spring @Autowired字段为空?

注意:这是针对常见问题的规范答案.

我有一个Spring @Serviceclass(MileageFeeCalculator),它有一个@Autowiredfield(rateService),但该字段是null我尝试使用它时.日志显示正在创建MileageFeeCalculatorbean和MileageRateServicebean,但NullPointerException每当我尝试mileageCharge在我的服务bean上调用该方法时,我都会得到.为什么Spring没有自动装配领域?

控制器类:

@Controller
public class MileageFeeController {    
    @RequestMapping("/mileage/{miles}")
    @ResponseBody
    public float mileageFee(@PathVariable int miles) {
        MileageFeeCalculator calc = new MileageFeeCalculator();
        return calc.mileageCharge(miles);
    }
}
Run Code Online (Sandbox Code Playgroud)

服务类:

@Service
public class MileageFeeCalculator {

    @Autowired
    private MileageRateService rateService; // <--- should be autowired, is null

    public float mileageCharge(final int miles) {
        return (miles * rateService.ratePerMile()); // <--- throws NPE
    }
}
Run Code Online (Sandbox Code Playgroud)

应该自动装配的服务bean,MileageFeeCalculator但它不是:

@Service …
Run Code Online (Sandbox Code Playgroud)

java null spring nullpointerexception autowired

555
推荐指数
14
解决办法
42万
查看次数

访问onCreate()中的视图的NullPointerException

这是针对StackOverflow上经常发布的问题的规范问题.

我正在关注一个教程.我使用向导创建了一个新活动.我NullPointerException试图在我的活动中使用Views获取方法时得到.findViewById()onCreate()

活动onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    View something = findViewById(R.id.something);
    something.setOnClickListener(new View.OnClickListener() { ... }); // NPE HERE

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}
Run Code Online (Sandbox Code Playgroud)

布局XML(fragment_main.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="packagename.MainActivity$PlaceholderFragment" >

    <View
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/something" />

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

java android nullpointerexception android-fragments

113
推荐指数
2
解决办法
2万
查看次数

抓住Throwable是不好的做法?

赶上是不好的做法Throwable

例如这样的事情:

try {
    // Some code
} catch(Throwable e) {
    // handle the exception
}
Run Code Online (Sandbox Code Playgroud)

这是一种不好的做法还是我们应该尽可能具体?

java exception-handling throwable

100
推荐指数
10
解决办法
8万
查看次数

Java:为什么我们可以将顶级类定义为私有?

为什么Java允许顶级类被声明为私有?除了"我们无法访问私人课程"之外,还有其他原因吗?

java

45
推荐指数
5
解决办法
7万
查看次数

如何更新Maven POM中的属性?

我有两个顶级Maven项目,backend并且frontend以各自的速度推进版本.由于每个模块都有多个模块,因此我dependencyManagement在父/聚合POM 中的部分中定义了我的依赖项版本,并使用属性作为版本号.

我想用版本号干净地更新属性frontend,最好随意更新,但我可以忍受要求实时上游版本匹配.我尝试过使用versions:update-property,但这个目标似乎完全不起作用; 无论是否真的有匹配的上游版本,我得到这个调试输出:

$ mvn versions:update-property -Dproperty=frontend.version -DnewVersion=0.13.2  -DautoLinkItems=false -X
...
[DEBUG] Searching for properties associated with builders
[DEBUG] Property ${frontend.version}
[DEBUG] Property ${frontend.version}: Looks like this property is not associated with any dependency...
[DEBUG] Property ${frontend.version}: Set of valid available versions is [0.9.0, 0.9.1, 0.9.2, 0.9.3, 0.9.4, 0.9.5, 0.10.0, 0.10.1, 0.11.0, 0.12.0, 0.13.0, 0.13.1, 0.13.2, 0.13.3]
[DEBUG] Property ${frontend.version}: Restricting results to 0.13.2
[DEBUG] Property ${frontend.version}: Current winner …
Run Code Online (Sandbox Code Playgroud)

pom.xml maven versions-maven-plugin

26
推荐指数
3
解决办法
2万
查看次数

你能用mockito(1.10.17)在接口中使用默认方法吗?

我是mockito的忠实粉丝,不幸的是,对于我使用Java 8的一个项目,它失败了...

场景:

public final class MockTest
{
    @Test
    public void testDefaultMethodsWithMocks()
    {
        final Foo foo = mock(Foo.class);

        //when(foo.bar()).thenCallRealMethod();

        assertThat(foo.bar()).isEqualTo(42);
    }

    @FunctionalInterface
    private interface Foo
    {
        int foo();

        default int bar()
        {
            return 42;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,测试失败并foo.bar()返回0.

当我取消注释该when()行时,我得到一个堆栈跟踪...

java.lang.NoSuchMethodError: java.lang.Object.bar()I
    at com.github.fge.lambdas.MockTest.testDefaultMethodsWithMocks(MockTest.java:18)
Run Code Online (Sandbox Code Playgroud)

这是maven上最新的稳定版本; 谷歌搜索周围没有告诉我关于Java 8中这个新功能的模拟状态...

你能否以其他方式使其工作,而不是实现接口和spy()它们(这是有效的)?

java mockito java-8 default-method

21
推荐指数
3
解决办法
8299
查看次数

从同步方法调用同步方法的同步成本是多少?

这之间的表现有什么不同吗?

synchronized void x() {
    y();
}

synchronized void y() {
}
Run Code Online (Sandbox Code Playgroud)

还有这个

synchronized void x() {
    y();
}

void y() {
}
Run Code Online (Sandbox Code Playgroud)

java concurrency synchronization

18
推荐指数
2
解决办法
3169
查看次数

在JAVA中使用注释启动时加载

我有这个代码,

@WebServlet(value="/initializeResources", loadOnStartup=1)
public class InitializeResources extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      System.out.println("HEREEEE");
  }

}
Run Code Online (Sandbox Code Playgroud)

但是,当Web应用程序启动时,servlet无法启动.

如何在Servlet Annotation上启动加载?

我的Servlet API是3.0,我使用Tomcat 7

java tomcat annotations servlets

13
推荐指数
2
解决办法
2万
查看次数

如何延迟Spring @Conditional配置注释的评估?

我有一个Spring @Configuration类,它应该在环境中设置特定属性值时注册bean.我编写了一个自定义Condition实现,检查该值是否存在,并且当我在Spring Boot中启动应用程序时它可以工作,但是在运行JUnit测试时从未注册过bean.我调试了应用程序并确定在实例化Condition之前正在评估PropertySourcesPlaceholderConfigurer它.

我修改了我Condition的实现ConfigurationCondition并在REGISTER_BEAN阶段中指定了评估.在实例化configurer之前仍然调用该方法,但是当我从属性文件中添加或删除属性时,已注册的bean现在来去.

这是重新评估评估的最佳方式吗?这是ConfigurationCondition接口的用途,还是我现在不小心让它上班?

@Conditional(PropertyCondition.class)
@Configuration
public class PostbackUrlConfiguration {
    @Value("${serviceName.postbackUrl}")
    String postbackUrl;

    @Bean
    public PostbackUrlProvider provider() {
        return new FixedUrlProvider(postbackUrl);
    }
}
Run Code Online (Sandbox Code Playgroud)

 

public class PropertyCondition implements ConfigurationCondition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return context.getEnvironment().containsProperty("serviceName.postbackUrl");
    }

    @Override
    public ConfigurationPhase getConfigurationPhase() {
        return ConfigurationPhase.REGISTER_BEAN;
    }
}
Run Code Online (Sandbox Code Playgroud)

测试配置是我测试用例的静态类:

@Configuration
@ComponentScan
@PropertySource("classpath:/postback.properties")
@Import(PostbackUrlConfiguration.class)
public static class TestConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer …
Run Code Online (Sandbox Code Playgroud)

spring spring-java-config

12
推荐指数
1
解决办法
4076
查看次数

生成指定范围内的随机数 - 各种情况(int,float,inclusive,exclusive)

给定一个Math.random()函数,它返回一个介于[0,1)和min max值之间的数字来指定范围,我们如何为以下情况生成数字:

我们想要整数的情况:

  • A: (min,max) ?
  • B: [min,max) return Math.floor(Math.random() * (max - min)) + min;
  • C: (min,max] ?
  • D: [min,max] return Math.floor(Math.random() * (max - min + 1)) + min;

我们想浮动的情况:

  • A: (min,max) ?
  • B: [min,max) return Math.random() * (max - min) + min;
  • C: (min,max] ?
  • D: [min,max] ?

javascript random floating-point integer range

12
推荐指数
1
解决办法
647
查看次数