我的服务bean在构造函数中设置了两个公共字段:
@Service
public class MyService {
private static final Logger log = LoggerFactory.getLogger(MyService.class);
public Boolean nativeHome;
public String url;
@Autowired
public MyService(
@Value("${homepage.native}") Boolean nativeHome,
@Value("${homepage.url}") String url) {
this.nativeHome = nativeHome;
this.url = url;
log.debug(this.nativeHome + ""); // not null
log.debug(this.url); // not null
}
}
此bean通过其构造函数注入控制器组件:
@RestController
public class MyController {
private static final Logger log = LoggerFactory.getLogger(MyController.class);
private MyService myService;
@Autowired
public MyController(MyService myService) {
this.myService = myService;
log.debug(this.myService.nativeHome + ""); // null
log.debug(this.myService.url); // null
}
}
spring引导日志以及logger调试消息表明,这两个字段在servicebean中设置正确,但它们是错误的 null
在控制器bean中:
15:47:44.397 [main] DEBUG c.r.spring.service.MyService.<init>(40) - false
15:47:44.397 [main] DEBUG c.r.spring.service.MyService.<init>(41) - http://...
[...]
15:47:46.160 [main] DEBUG c.r.s.controller.MyController.<init>(34) - null
15:47:46.160 [main] DEBUG c.r.s.controller.MyController.<init>(35) - null
如果我将这两个字段声明为 private
并在控制器中使用getter,则这两个字段不是 null
不再。为什么会这样?
我带来了完整的项目设置的完整性,即使它可能不相关的问题。
Spring版本:5.2.8.0
春根 applicationContext.xml
```
<context:annotation-config />
<aop:aspectj-autoproxy />
<context:component-scan base-package="c.r.spring">
<context:exclude-filter type="regex" expression="c\.r\.spring\.controller.*"/>
</context:component-scan>
<import resource="classpath:spring/spring-jdbc.xml" />
<mvc:annotation-driven>
<mvc:path-matching trailing-slash="true" />
</mvc:annotation-driven>
<mvc:default-servlet-handler />
<mvc:cors>
<mvc:mapping path="/**"
allowed-origins="http://devel.r.com:3000"
allowed-methods="GET, POST, PUT, DELETE, OPTIONS"
allowed-headers="Authorization, Content-Type"
exposed-headers="Access-Control-Allow-Origin"
allow-credentials="true" />
</mvc:cors>
<context:component-scan base-package="c.r.spring.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/spring/views/" />
<property name="suffix" value=".jsp" />
</bean>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
暂无答案!
目前还没有任何答案,快来回答吧!