Я просмотрел около 30 веб-страниц и 50 статей об этом, и он все еще не работает.
Вот мой код, очень простой. Я начинаю только весной.можно найти в контексте элемента: property-placeholder. Весна 4
App.java
package com.procus.spring.simple.simple;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
*
* @author procus
*/
public class App {
public static void main(String[] args) {
ApplicationContext con = new ClassPathXmlApplicationContext("SpringBeans.xml");
SampleSimpleApplication sam = (SampleSimpleApplication) con.getBean("sam");
sam.run(args);
}
}
SampleSimpleApplication.java
package com.procus.spring.simple.simple;
import com.procus.calculator.basic.BasicCalculator;
import com.procus.spring.simple.simple.service.HelloWorldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackageClasses = BasicCalculator.class)
public class SampleSimpleApplication implements CommandLineRunner {
// intentional error
@Autowired
BasicCalculator calculator;
// Simple example shows how a command line spring application can execute an
// injected bean service. Also demonstrates how you can use @Value to inject
// command line args ('--name=whatever') or application properties
@Autowired
private HelloWorldService helloWorldService;
public SampleSimpleApplication() {
}
@Override
public void run(String... args) {
System.out.println(this.helloWorldService.getHelloMessage());
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleSimpleApplication.class, args);
}
}
HelloWorldService.java
package com.procus.spring.simple.simple.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.stereotype.Component;
@Component
@Configuration
@PropertySource(value = { "classpath:application.properties" })
public class HelloWorldService {
@Value("${app.name:World}")
private String name;
public String getHelloMessage() {
return "Hello " + this.name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
SpringBeans.xml папка
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<context:property-placeholder location="classpath*:application.properties"/>
<bean id="DBProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<value>classpath*:application.properties</value>
</property>
</bean>
<bean id="sam" class="com.procus.spring.simple.simple.SampleSimpleApplication"/>
<bean id="serv" class="com.procus.spring.simple.simple.service.HelloWorldService">
<property name="name" value="Jano" />
</bean>
<bean id="calc" class="com.procus.calculator.basic.BasicCalculator">
<constructor-arg value="1.0"/>
</bean>
</beans>
И в ресурсах моего application.properties файл, который содержит только app.name = Фил
Исключение в потоке "основной" org.springframework. beans.factory.xml.XmlBeanDefinitionStoreException: Строка 12 в XML-документе из ресурса пути к классу [SpringBeans.xml] - недействительна; Вложенное исключение - org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 81; cvc-complex-type.2.4.c: Подстановочный шаблон является строгим, но для элемента не найдено декларации «context: property-placeholder».
Я действительно пробовал большинство решений, которые я нашел в stackoverflow и нескольких других форумах. Я очень новый весной, и я буду признателен за любую помощь.
теперь возвращает org.springframework.beans.factory.NoSuchBeanDefinitionException: Нет квалификационную боб типа [java.lang .String], найденная для зависимости: ожидается как минимум 1 компонент, который квалифицируется как кандидат на автоуровень для этой зависимости. Аннотации зависимостей: {@ org.springframework.beans.factory.annotation.Value (value = $ {app.name:World)} –
В вашем HelloWorldService.java вы пишете «$ {app.name:World», скобка в не complete, "$ {app.name:World}} – Waqar
Och извините за это, я исправил его и до сих пор возвращаю ту же ошибку –