Spring - Как использовать Внедрение зависимости Spring для записи Автономного JAVA-приложения

let initialString = "atttbcdddd"
let myInitialString = initialString + " "

var currentLetter: Character = " "
var currentCount = 1
var answer = ""

for (_, char) in myInitialString.enumerated(){
    if char == currentLetter {
        currentCount += 1
    } else {
        if currentCount > 1 {
            answer += String(currentCount)
        }
        answer += String(char)
        currentCount = 1
        currentLetter = char
   }
}
print(answer)
8
задан Benjamin 6 November 2013 в 21:19
поделиться

5 ответов

предположим, у вас есть:

class Bean1 {
  Bean2 bean2;
}

class Bean2 {
  String data;
}

файл context.xml

<bean id="bean1" class="Bean1">
  <property name="bean2" ref="bean2" />
</bean>

<bean id="bean2" class="Bean2" />

, тогда это должно быть правдой

ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"context.xml"});
Bean1 bean1 = (Bean1) context.getBean("bean1");

// bean1.bean2 should not be null here.
18
ответ дан 5 December 2019 в 05:46
поделиться

Как вы подтвердили, что ваши бобы неправильно подключены? Одна из распространенных проблем - файл конфигурации xml находится не в нужном месте. Не могли бы вы предоставить нам дополнительную информацию, например, макет вашего проекта и код, который вы используете для получения bean-компонентов из контейнера?

0
ответ дан 5 December 2019 в 05:46
поделиться

Если вы добавите ведение журнала log4j в свое приложение, вы должны увидеть каскад выводимых сообщений, которые многое расскажут о том, что Spring делает, а что не делает. Если у вас нет такой обратной связи, вы в темноте. Возможно, вам удастся найти ответ, просто получив дополнительную информацию о Spring из log4j.

0
ответ дан 5 December 2019 в 05:46
поделиться

Are you calling context.getBean("beanName") to get a reference to the bean or are you doing a new SomeClass()? If you do it through getBean() then the injected properties should be set.

Also, be sure to use the same bean factory (ClassPathXmlApplicationContext instance) for retrieving all your beans. This should most likely be static final and used by the entire application.

0
ответ дан 5 December 2019 в 05:46
поделиться

you can use autowiring support provided by spring, in order to inject dependencies (and possibly apply post processors) to an object that is not part of the application context.

In your case, this object is your standalone application.

Here is the way to achieve this. In this example, I use @Autowired (for b1), traditional DI (for b2) and initialization hook for b3. The autowiring support with annotations assumes you have defined the appropriate spring post-processor in your application context (e.g. by declaring ).

public class StandaloneApp implements InitializingBean {
  @Autowired private Bean1 b1;
  private Bean2 b2;
  private Bean3 b3;

  public void afterPropertiesSet() throws Exception {
    this.b3 = new Bean3(b1, b2);
  }

  public void setB2(Bean2 b2) {
    this.b2 = b2;
  }

  public static void main(String... args) {
    String[] locations = // your files relative to the classpath
    ApplicationContext ac = new ClasspathXmlApplicationContext(locations);
    // or use FileSystemXmlApplicationContext if the files are not in the classpath

    StandaloneApp app = new StandaloneApp();
    AutowireCapableBeanFactory acbf = ac.getAutowireCapableBeanFactory();
    acbf.autowireBeanProperties(app, AUTOWIRE_BY_NAME, false);
    acbf.initializeBean(app, "standaloneApp"); // any name will work
  }
}

In this example, all b1, b2 and b3 should be non-null (assuming b1 and b2 beans exist in your application context).

I haven't tested it (might not even compile due to some typo), but the idea is in the last 3 lines. See the javadocs for AutowireCapableBeanFactory and mentionned methods to see exactly what happens.

9
ответ дан 5 December 2019 в 05:46
поделиться
Другие вопросы по тегам:

Похожие вопросы: